Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made a in memory cache module and added it to /tasks endpoint #713

Merged
merged 4 commits into from
Sep 25, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added option to set global cache & renamed 'globalStore' to 'cachePool'
  • Loading branch information
yash committed Sep 21, 2022
commit 86360211d433516a5e3e9610866431d6432615d7
20 changes: 13 additions & 7 deletions utils/cache.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
const CACHEEXPIRYTIME = 2; // Default cache expriy time in Minutes
const CACHESIZE = 10; // Default maximum size for cache pool (in Megabytes)
const minutesToMilliseconds = (minutes) => minutes * 60000; // Converts given minutes into milliseconds

const globalStore = () => {
/**
* Cache pool to get and store API responses
* @param {Object} [opt] options for cache pool
* @param {number} opt.maximumSize Maximum size of the cache pool in Megabytes (MB)
*/
const cachePool = (opt = { maximumSize: CACHESIZE }) => {
const cacheStore = new Map();
let hits = 0;

Expand Down Expand Up @@ -30,8 +36,8 @@ const globalStore = () => {
};

/**
* Add API response to our cacheStore.
* @param {string} key {string}
* Add API response to cacheStore.
* @param {string} key
* @param {Object} value Value to be stored inside the cache.
* @param {number} value.priority Priority of the api
* @param {number} value.expiry Expiry time of api
Expand All @@ -50,8 +56,8 @@ const globalStore = () => {
return { get, set, hits, cacheStore };
};

// Initialize globalstore to be used.
const store = globalStore();
// Initialize cache pool.
const pool = cachePool();

/**
* Caching middleware for API resposnes.
Expand All @@ -63,7 +69,7 @@ const store = globalStore();
const cache = (data = { priority: 2, expiry: CACHEEXPIRYTIME }) => {
return async (req, res, next) => {
yesyash marked this conversation as resolved.
Show resolved Hide resolved
const key = "__cache__" + req.method + req.originalUrl;
const dataInCache = store.get(key);
const dataInCache = pool.get(key);
yesyash marked this conversation as resolved.
Show resolved Hide resolved

if (dataInCache) {
res.send(dataInCache);
Expand Down Expand Up @@ -95,7 +101,7 @@ const cache = (data = { priority: 2, expiry: CACHEEXPIRYTIME }) => {
size: Buffer.byteLength(apiResponse),
};

store.set(key, cacheValue);
pool.set(key, cacheValue);
return oldEnd.apply(res, [chunk, ...args]);
};

Expand Down