Last active
March 29, 2020 19:50
-
-
Save ahallora/603e28e18b001407a744d6536a79467b to your computer and use it in GitHub Desktop.
Simple AWS Lambda Container In-Memory Cache Controller for Node.js / ES6
This file contains 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 { 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); | |
} | |
} |
This file contains 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
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