Last active
December 27, 2022 14:55
-
-
Save bradoyler/b162c591e2db6a07b023f0e74086bc2a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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