forked from freeCodeCamp/freeCodeCamp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdonation.js
More file actions
77 lines (67 loc) · 2.23 KB
/
Copy pathdonation.js
File metadata and controls
77 lines (67 loc) · 2.23 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Observable } from 'rx';
import debug from 'debug';
import { reportError } from '../middlewares/error-reporter';
import InMemoryCache from '../utils/in-memory-cache';
const log = debug('fcc:boot:donate');
const fiveMinutes = 1000 * 60 * 5;
export default function(Donation) {
let activeDonationUpdateInterval = null;
const activeDonationCountCacheTTL = fiveMinutes;
const activeDonationCountCache = InMemoryCache(0, reportError);
const activeDonationsQuery$ = () =>
Donation.find$({
// eslint-disable-next-line no-undefined
where: { endDate: undefined }
}).map(instances => instances.length);
function cleanUp() {
if (activeDonationUpdateInterval) {
clearInterval(activeDonationUpdateInterval);
}
return;
}
process.on('exit', cleanUp);
Donation.on('dataSourceAttached', () => {
Donation.find$ = Observable.fromNodeCallback(Donation.find.bind(Donation));
Donation.findOne$ = Observable.fromNodeCallback(
Donation.findOne.bind(Donation)
);
seedTheCache()
.then(setupCacheUpdateInterval)
.catch(err => {
const errMsg = `Error caught seeding the cache: ${err.message}`;
err.message = errMsg;
reportError(err);
});
});
function seedTheCache() {
return new Promise((resolve, reject) =>
Observable.defer(activeDonationsQuery$).subscribe(count => {
log('activeDonator count: %d', count);
activeDonationCountCache.update(() => count);
return resolve();
}, reject)
);
}
function setupCacheUpdateInterval() {
activeDonationUpdateInterval = setInterval(
() =>
Observable.defer(activeDonationsQuery$).subscribe(
count => {
log('activeDonator count: %d', count);
return activeDonationCountCache.update(() => count);
},
err => {
const errMsg = `Error caught updating the cache: ${err.message}`;
err.message = errMsg;
reportError(err);
}
),
activeDonationCountCacheTTL
);
return null;
}
function getCurrentActiveDonationCount$() {
return Observable.of(activeDonationCountCache.get());
}
Donation.getCurrentActiveDonationCount$ = getCurrentActiveDonationCount$;
}