Created
June 13, 2024 19:40
-
-
Save ERmilburn02/84765c1d62ca294e22369fe9eb9d45a7 to your computer and use it in GitHub Desktop.
An adapter for Lucia, using JavaScript maps as the database
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 type { Adapter, DatabaseSession, DatabaseUser, UserId } from "lucia"; | |
| export interface Database { | |
| users: Map<UserId, DatabaseUser>; | |
| sessions: Map<string, DatabaseSession>; | |
| } | |
| export class MapAdapter implements Adapter { | |
| private readonly _database: Database; | |
| constructor(database: Database) { | |
| this._database = database; | |
| } | |
| public async getSessionAndUser( | |
| sessionId: string | |
| ): Promise<[session: DatabaseSession | null, user: DatabaseUser | null]> { | |
| const databaseSession = this._database.sessions.get(sessionId); | |
| if (!databaseSession) { | |
| const session = null; | |
| const user = null; | |
| return [session, user]; | |
| } | |
| const databaseUser = this._database.users.get(databaseSession.userId); | |
| if (!databaseUser) { | |
| const session = null; | |
| const user = null; | |
| return [session, user]; | |
| } | |
| const session = databaseSession; | |
| const user = databaseUser; | |
| return [session, user]; | |
| } | |
| public async getUserSessions(userId: string): Promise<DatabaseSession[]> { | |
| const sessions: DatabaseSession[] = []; | |
| this._database.sessions.forEach((session) => { | |
| if (session.userId == userId) { | |
| sessions.push(session); | |
| } | |
| }); | |
| return sessions; | |
| } | |
| public async setSession(session: DatabaseSession): Promise<void> { | |
| this._database.sessions.set(session.id, session); | |
| } | |
| public async updateSessionExpiration( | |
| sessionId: string, | |
| expiresAt: Date | |
| ): Promise<void> { | |
| const currentSession = this._database.sessions.get(sessionId); | |
| if (!currentSession) return; | |
| currentSession.expiresAt = expiresAt; | |
| this._database.sessions.set(sessionId, currentSession); | |
| } | |
| public async deleteSession(sessionId: string): Promise<void> { | |
| this._database.sessions.delete(sessionId); | |
| } | |
| public async deleteUserSessions(userId: string): Promise<void> { | |
| this._database.sessions.forEach((session, key) => { | |
| if (session.userId == userId) { | |
| this._database.sessions.delete(key); | |
| } | |
| }); | |
| } | |
| public async deleteExpiredSessions(): Promise<void> { | |
| const now = new Date(); | |
| this._database.sessions.forEach((session, key) => { | |
| if (session.expiresAt < now) { | |
| this._database.sessions.delete(key); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment