Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active March 29, 2020 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahallora/603e28e18b001407a744d6536a79467b to your computer and use it in GitHub Desktop.
Save ahallora/603e28e18b001407a744d6536a79467b to your computer and use it in GitHub Desktop.
Simple AWS Lambda Container In-Memory Cache Controller for Node.js / ES6
import { LambdaCacheController } from "libs/LambdaCacheController";
// make it out side handler to make it in-memory cachable in lambda container
const lambdaCache = new LambdaCacheController();
export async function main(event) {
try {
// get content from cache (if possible)
let data = await lambdaCache.getValue();
if (!data) {
// fetch your data here
const projects = await getItemsFromCollection("projects");
if (!projects) throw Error("projects returned error");
// save content to cache
await lambdaCache.setValue(projects.items || []);
// set your data to contain the cached value + expireIn meta data
data = await lambdaCache.getValue();
}
// return data nicely
return success({
data: data.value,
expiresIn: data.expiresIn,
});
} catch (e) {
console.log(e);
return failure(e);
}
}
export class LambdaCacheController {
constructor() {
this.value = null;
this.timestamp = null;
this.ttl = 3000000; // default 5 minutes
}
async getValue() {
return new Promise((resolve, reject) => {
try {
const { timestamp, value, ttl } = this;
const expiresIn = timestamp + ttl - Date.now();
resolve(
value && timestamp && expiresIn > 0
? {
value: JSON.parse(value),
expiresIn,
}
: null
);
} catch (e) {
console.error(e);
reject(e);
}
});
}
async setValue(valueToCache, timeToLive) {
return new Promise((resolve, reject) => {
try {
this.value = JSON.stringify(valueToCache);
this.timestamp = Date.now();
if (timeToLive) this.ttl = timeToLive;
resolve(true);
} catch (e) {
console.error(e);
reject(e);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment