somod-chat-service
Version:
Serverless Chat Service from SOMOD
62 lines (61 loc) • 1.53 kB
JavaScript
export const cache = (max, ttl) => {
const cacheTtl = ttl;
const nodes = {};
let first = undefined;
let last = undefined;
let size = 0;
const remove = (key) => {
const node = nodes[key];
if (node.next) {
node.next.previous = node.previous;
}
else {
last = node.previous?.content.key;
}
if (node.previous) {
node.previous.next = node.next;
}
else {
first = node.next?.content.key;
}
size--;
delete nodes[key];
};
const add = (key, value) => {
const node = {
content: {
key,
cachedAt: Date.now(),
value
}
};
nodes[key] = node;
size++;
if (first) {
node.next = nodes[first];
nodes[first].previous = node;
}
first = key;
};
const get = async (key, fetcher, ttl) => {
const node = nodes[key];
let value = node?.content.value;
const now = Date.now();
if (node === undefined ||
(ttl && node.content.cachedAt < now - ttl) ||
(cacheTtl && node.content.cachedAt < now - cacheTtl)) {
value = await fetcher();
}
if (node) {
remove(node.content.key);
}
add(key, value);
if (size > max && last) {
remove(last);
}
return value;
};
return {
get
};
};