forked from marklagendijk/node-toogoodtogo-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoller.js
51 lines (44 loc) · 1.79 KB
/
poller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const _ = require('lodash');
const { interval } = require('rxjs');
const { from, of } = require('rxjs');
const { flatMap, startWith, filter, map, withLatestFrom, retry, catchError } = require('rxjs/operators');
const { config } = require('./config');
const api = require('./api');
const MINIMAL_POLLING_INTERVAL = 15000;
const MINIMAL_AUTHENTICATION_INTERVAL = 3600000;
module.exports = {
pollFavoriteBusinesses
};
function pollFavoriteBusinesses(){
const pollingIntervalInMs = getInterval('api.pollingIntervalInMs', MINIMAL_POLLING_INTERVAL);
const authenticationIntervalInMs = getInterval('api.authenticationIntervalInMS', MINIMAL_AUTHENTICATION_INTERVAL);
const authentication$ = interval(authenticationIntervalInMs).pipe(
startWith(0),
flatMap(() => from(api.login()).pipe(
retry(2),
catchError(logError),
filter(authentication => !!authentication)
))
);
return interval(pollingIntervalInMs).pipe(
startWith(0),
withLatestFrom(authentication$),
flatMap(() => from(api.listFavoriteBusinesses()).pipe(
retry(2),
catchError(logError),
filter(response => !!_.get(response, 'items')),
map(response => response.items)
))
);
}
function logError(error){
console.error(`Error ${_.get(error, 'statusCode')} during ${_.get(error, 'options.method')} ${_.get(error, 'options.baseUrl')}${_.get(error, 'options.url')}:
${JSON.stringify(_.get(error, 'response.body.errors'), null, 4)}`);
return of(null);
}
function getInterval(configPath, minimumIntervalInMs){
const configuredIntervalInMs = config.get(configPath);
return _.isFinite(configuredIntervalInMs) ?
Math.max(configuredIntervalInMs, minimumIntervalInMs) :
minimumIntervalInMs;
}