memorium/lib/cache/documents.ts

58 lines
1.1 KiB
TypeScript

import { Document } from "@lib/documents.ts";
import * as cache from "@lib/cache/cache.ts";
type DocumentsCache = {
lastUpdated: number;
documents: Document[];
};
const CACHE_INTERVAL = 5000; // 5 seconds;
const CACHE_KEY = "documents";
export async function getDocuments() {
const docs = await cache.get<DocumentsCache>(CACHE_KEY);
if (!docs) return;
if (Date.now() > docs.lastUpdated + CACHE_INTERVAL) {
return;
}
return docs.documents;
}
export function setDocuments(documents: Document[]) {
return cache.set(
CACHE_KEY,
JSON.stringify({
lastUpdated: Date.now(),
documents,
}),
);
}
type DocumentCache = {
lastUpdated: number;
content: string;
};
export async function getDocument(id: string) {
const doc = await cache.get<DocumentCache>(CACHE_KEY + "/" + id);
if (!doc) return;
if (Date.now() > doc.lastUpdated + CACHE_INTERVAL) {
return;
}
return doc.content;
}
export async function setDocument(id: string, content: string) {
await cache.set(
CACHE_KEY + "/" + id,
JSON.stringify({
lastUpdated: Date.now(),
content,
}),
);
}