Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active Jul 28, 2020
Embed
What would you like to do?
import NodeCache from 'node-cache'; // or 'redis'
class CacheService {
constructor(ttlSeconds) {
// this could also be redis
this.cache = new NodeCache({ stdTTL: ttlSeconds, checkperiod: ttlSeconds * 0.2, useClones: false });
}
get(key, storeFunction) {
const value = this.cache.get(key);
if (value) {
return Promise.resolve(value);
}
return storeFunction().then((result) => {
this.cache.set(key, result);
return result;
});
}
}
export default CacheService;
import DB from '../db';
import CacheService from '../cache.service';
const ttl = 60 * 60 * 1; // cache for 1 Hour
const cache = new CacheService(ttl); // Create a new cache service instance
const DataService = {
// ...
getDocsById(docID) {
const selectQuery = `SELECT * FROM table WHERE docID = ${docID}`;
return cache.get(docID, () => DB.then((connection) =>
connection.query(selectQuery).then((rows) => {
return rows[0];
})
)).then((result) => {
return result;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment