feat: cache for session store in db

This commit is contained in:
Huskydog9988
2025-04-01 21:32:13 -04:00
parent 88a5dc2a58
commit 0f35d4a445
3 changed files with 19 additions and 1 deletions

View File

@ -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",

View File

@ -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<string, Session>({
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<T>(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,

View File

@ -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"