diff --git a/package.json b/package.json index f0a426e..fc550ff 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "fast-fuzzy": "^1.12.0", "file-type-mime": "^0.4.3", "jdenticon": "^3.3.0", + "lru-cache": "^11.1.0", "micromark": "^4.0.1", "moment": "^2.30.1", "nuxt": "^3.13.2", diff --git a/server/internal/session/db.ts b/server/internal/session/db.ts index 6a85068..d514791 100644 --- a/server/internal/session/db.ts +++ b/server/internal/session/db.ts @@ -1,11 +1,18 @@ -import { json } from "stream/consumers"; +import { LRUCache } from "lru-cache"; import prisma from "../db/database"; import { Session, SessionProvider } from "./types"; import { Prisma } from "@prisma/client"; export default function createDBSessionHandler(): SessionProvider { + const cache = new LRUCache({ + max: 50, // number of items + ttl: 30 * 100, // 30s (in ms) + }); + return { async setSession(token, data) { + cache.set(token, data); + // const strData = JSON.stringify(data); await prisma.session.upsert({ where: { @@ -24,6 +31,7 @@ export default function createDBSessionHandler(): SessionProvider { async updateSession(token, key, data) { const newObj: { [key: string]: any } = {}; newObj[key] = data; + cache.set(token, newObj); const session = await prisma.session.upsert({ where: { @@ -60,6 +68,9 @@ export default function createDBSessionHandler(): SessionProvider { return false; }, async getSession(token: string) { + const cached = cache.get(token); + if (cached !== undefined) return cached as T; + const result = await prisma.session.findUnique({ where: { token, @@ -69,6 +80,7 @@ export default function createDBSessionHandler(): SessionProvider { return result.data as T; }, async clearSession(token) { + cache.delete(token); await prisma.session.delete({ where: { token, diff --git a/yarn.lock b/yarn.lock index 7817ed9..e221510 100644 --- a/yarn.lock +++ b/yarn.lock @@ -4282,6 +4282,11 @@ lru-cache@^10.2.0, lru-cache@^10.4.3: resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.4.3.tgz#410fc8a17b70e598013df257c2446b7f3383f119" integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ== +lru-cache@^11.1.0: + version "11.1.0" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-11.1.0.tgz#afafb060607108132dbc1cf8ae661afb69486117" + integrity sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A== + lru-cache@^5.1.1: version "5.1.1" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920"