@lifeworld/adapter-drizzle
Version:
Drizzle ORM adapter for Lucia
97 lines (96 loc) • 3.2 kB
JavaScript
import { eq, lte } from "drizzle-orm";
export class DrizzleSQLiteAdapter {
db;
sessionTable;
userTable;
constructor(db, sessionTable, userTable) {
this.db = db;
this.sessionTable = sessionTable;
this.userTable = userTable;
}
async deleteSession(sessionId) {
await this.db.delete(this.sessionTable).where(eq(this.sessionTable.id, sessionId));
}
async deleteUserSessions(userId) {
await this.db.delete(this.sessionTable).where(eq(this.sessionTable.userId, userId));
}
async getSessionAndUser(sessionId) {
// https://github.com/drizzle-team/drizzle-orm/issues/555
const [databaseSession, databaseUser] = await Promise.all([
this.getSession(sessionId),
this.getUserFromSessionId(sessionId)
]);
return [databaseSession, databaseUser];
}
async getSession(sessionId) {
const result = await this.db
.select()
.from(this.sessionTable)
.where(eq(this.sessionTable.id, sessionId));
if (result.length !== 1)
return null;
return transformIntoDatabaseSession(result[0]);
}
async getUserFromSessionId(sessionId) {
const { _, $inferInsert, $inferSelect, getSQL, shouldOmitSQLParens, ...userColumns } = this.userTable;
const result = await this.db
.select(userColumns)
.from(this.sessionTable)
.innerJoin(this.userTable, eq(this.sessionTable.userId, this.userTable.id))
.where(eq(this.sessionTable.id, sessionId));
if (result.length !== 1)
return null;
return transformIntoDatabaseUser(result[0]);
}
async getUserSessions(userId) {
const result = await this.db
.select()
.from(this.sessionTable)
.where(eq(this.sessionTable.userId, userId))
.all();
return result.map((val) => {
return transformIntoDatabaseSession(val);
});
}
async setSession(session) {
await this.db
.insert(this.sessionTable)
.values({
id: session.id,
userId: session.userId,
expiresAt: Math.floor(session.expiresAt.getTime() / 1000),
...session.attributes
})
.run();
}
async updateSessionExpiration(sessionId, expiresAt) {
await this.db
.update(this.sessionTable)
.set({
expiresAt: Math.floor(expiresAt.getTime() / 1000)
})
.where(eq(this.sessionTable.id, sessionId))
.run();
}
async deleteExpiredSessions() {
await this.db
.delete(this.sessionTable)
.where(lte(this.sessionTable.expiresAt, Math.floor(Date.now() / 1000)));
}
}
function transformIntoDatabaseSession(raw) {
const { id, userId, expiresAt: expiresAtUnix, ...attributes } = raw;
return {
userId,
id,
expiresAt: new Date(expiresAtUnix * 1000),
attributes
};
}
function transformIntoDatabaseUser(raw) {
const { id, ...attributes } = raw;
return {
id,
attributes
};
}