feat: Use InMemoryCache to reducve load on db
This commit is contained in:
committed by
mrugesh mohapatra
parent
80c3c3ec55
commit
6475eadf82
@ -1,18 +1,50 @@
|
||||
import { Observable } from 'rx';
|
||||
import debug from 'debug';
|
||||
|
||||
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);
|
||||
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)
|
||||
);
|
||||
activeDonationsQuery$().subscribe(count => {
|
||||
log('activeDonator count: %d', count);
|
||||
return activeDonationCountCache.update(() => count);
|
||||
});
|
||||
|
||||
activeDonationUpdateInterval = setInterval(
|
||||
() =>
|
||||
activeDonationsQuery$().subscribe(count => {
|
||||
log('activeDonator count: %d', count);
|
||||
return activeDonationCountCache.update(() => count);
|
||||
}),
|
||||
activeDonationCountCacheTTL
|
||||
);
|
||||
});
|
||||
|
||||
function getCurrentActiveDonationCount$() {
|
||||
// eslint-disable-next-line no-undefined
|
||||
return Donation.find$({ where: { endDate: undefined } }).map(
|
||||
instances => instances.length
|
||||
);
|
||||
return Observable.of(activeDonationCountCache.get());
|
||||
}
|
||||
|
||||
Donation.getCurrentActiveDonationCount$ = getCurrentActiveDonationCount$;
|
||||
|
Reference in New Issue
Block a user