Last active
September 21, 2022 06:13
-
-
Save msurdi/05aa22880a12bd775154e65ef85ccfa3 to your computer and use it in GitHub Desktop.
Prisma express session store
This file contains 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 { Store } from "express-session"; | |
class PrismaSessionStore extends Store { | |
/** | |
* | |
* @param {import("@prisma/client").PrismaClient} db | |
*/ | |
constructor(db, { cleanupInterval } = {}) { | |
super(); | |
this.db = db; | |
this.isTouching = {}; | |
if (cleanupInterval) { | |
this.interval = setInterval( | |
() => this.clearExpiredSessions(), | |
cleanupInterval | |
); | |
} | |
} | |
async clearExpiredSessions() { | |
await this.db.session.deleteMany({ | |
where: { expiresAt: { lte: new Date() } }, | |
}); | |
} | |
async all(cb) { | |
const sessions = await this.db.session.findMany(); | |
const sessionsData = sessions.map((session) => JSON.parse(session.data)); | |
cb(null, sessionsData); | |
} | |
async destroy(sid, cb) { | |
await this.db.session.delete({ where: { sid } }); | |
return cb?.(); | |
} | |
async clear(cb) { | |
await this.db.session.deleteMany(); | |
return cb?.(); | |
} | |
async length(cb) { | |
const count = await this.db.session.count(); | |
return cb(null, count); | |
} | |
async get(sid, cb) { | |
const session = await this.db.session.findUnique({ where: { sid } }); | |
if (!session) { | |
return cb(null, null); | |
} | |
return cb(null, JSON.parse(session.data)); | |
} | |
async set(sid, session, cb) { | |
await this.db.session.upsert({ | |
where: { sid }, | |
update: { data: JSON.stringify(session) }, | |
create: { | |
sid, | |
data: JSON.stringify(session), | |
expiresAt: new Date(new Date() + session.cookie.originalMaxAge), | |
}, | |
}); | |
return cb(); | |
} | |
async touch(sid, session, cb) { | |
if (this.isTouching[sid]) { | |
return cb(); | |
} | |
this.isTouching[sid] = true; | |
try { | |
await this.db.session.update({ | |
where: { sid }, | |
data: { data: JSON.stringify(session) }, | |
}); | |
} finally { | |
delete this.isTouching[sid]; | |
} | |
return cb(); | |
} | |
} | |
export default PrismaSessionStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment