Skip to content

Instantly share code, notes, and snippets.

@mutaimwiti
Forked from morphatic/index.js
Created September 3, 2023 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutaimwiti/8fcb3fd18a3393c13d88566e56333a48 to your computer and use it in GitHub Desktop.
Save mutaimwiti/8fcb3fd18a3393c13d88566e56333a48 to your computer and use it in GitHub Desktop.
Example of polling a REST API every 1.5 seconds with Observables in NodeJS
/**
* Instructions
*
* 1. mkdir test
* 2. cd test
* 3. npm init
* 4. accept all defaults is fine
* 5. npm install @akanass/rx-http-request
* 6. paste code below into new file index.js
* 7. update username, password, other variables
* 8. node index
*/
// import necessary libraries
const Rx = require('rxjs/Rx');
const RxHR = require('@akanass/rx-http-request').RxHR;
// set up api requrest
let uri = 'http://api.timezonedb.com/v2/get-time-zone';
let qs = {
key: 'S3UJYQB3HFMI',
by: 'zone',
zone: 'America/New_York',
format: 'json'
};
// create polling source
let source = Rx.Observable.interval(1500).flatMap(() => RxHR.get(uri, {qs: qs}));
// control variable to let us know when to stop polling
let i = 0;
// start poll
let subscription = source.subscribe(
res => {
console.log(JSON.parse(res.body).formatted);
i++;
if(i > 5) {
subscription.unsubscribe();
}
},
err => {
console.log('error: ', err);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment