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

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