Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active December 27, 2022 14:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradoyler/b162c591e2db6a07b023f0e74086bc2a to your computer and use it in GitHub Desktop.
Save bradoyler/b162c591e2db6a07b023f0e74086bc2a to your computer and use it in GitHub Desktop.
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