Created
February 24, 2022 11:34
-
-
Save SagnikPradhan/251867bb21e89cc792a1a146bd44cdbf to your computer and use it in GitHub Desktop.
π Koa Session Prisma Store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PrismaClient } from "#/gen/prisma" | |
import { stores } from "koa-session" | |
const prisma = new PrismaClient() | |
export const SessionStore: stores = { | |
async get(key) { | |
return prisma.session.findUnique({ where: { id: key } }) | |
}, | |
async set(key, session, maxAge) { | |
if (typeof maxAge === "number") | |
setTimeout(() => { | |
this.destroy(key).catch((error: Error) => { | |
console.error(error) | |
}) | |
}, maxAge) | |
const data = { | |
id: key, | |
expiresAt: | |
typeof maxAge === "number" ? new Date(Date.now() + maxAge) : null, | |
...session.data, | |
} | |
return prisma.session.upsert({ | |
where: { id: key }, | |
update: data, | |
create: data, | |
}) | |
}, | |
async destroy(key) { | |
return prisma.session.delete({ where: { id: key } }) | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment