1import type {
2 Adapter,
3 DatabaseSession,
4 DatabaseUser,
5 RegisteredDatabaseSessionAttributes,
6 RegisteredDatabaseUserAttributes,
7} from "npm:lucia";
8
34 public async getSessionAndUser(
35 sessionId: string,
36 ): Promise<[session: DatabaseSession | null, user: DatabaseUser | null]> {
37 const [databaseSession, databaseUser] = await Promise.all([
38 this.getSession(sessionId),
39 this.getUserFromSessionId(sessionId),
40 ]);
41 return [databaseSession, databaseUser];
42 }
43
44 public async getUserSessions(userId: string): Promise<DatabaseSession[]> {
45 const result = await this.controller.getAll<SessionSchema>(
46 `SELECT * FROM ${this.escapedSessionTableName} WHERE user_id = ?`,
48 );
49 return result.map((val) => {
50 return transformIntoDatabaseSession(val);
51 });
52 }
53
54 public async setSession(databaseSession: DatabaseSession): Promise<void> {
55 const value: SessionSchema = {
56 id: databaseSession.id,
57 user_id: databaseSession.userId,
58 expires_at: Math.floor(databaseSession.expiresAt.getTime() / 1000),
59 ...databaseSession.attributes,
60 };
61 const entries = Object.entries(value).filter(([_, v]) => v !== undefined);
87 }
88
89 private async getSession(sessionId: string): Promise<DatabaseSession | null> {
90 const result = await this.controller.get<SessionSchema>(
91 `SELECT * FROM ${this.escapedSessionTableName} WHERE id = ?`,
93 );
94 if (!result) return null;
95 return transformIntoDatabaseSession(result);
96 }
97
98 private async getUserFromSessionId(sessionId: string): Promise<DatabaseUser | null> {
99 const result = await this.controller.get<UserSchema>(
100 `SELECT ${this.escapedUserTableName}.* FROM ${this.escapedSessionTableName} INNER JOIN ${this.escapedUserTableName} ON ${this.escapedUserTableName}.id = ${this.escapedSessionTableName}.user_id WHERE ${this.escapedSessionTableName}.id = ?`,
102 );
103 if (!result) return null;
104 return transformIntoDatabaseUser(result);
105 }
106}
117}
118
119interface SessionSchema extends RegisteredDatabaseSessionAttributes {
120 id: string;
121 user_id: string;
123}
124
125interface UserSchema extends RegisteredDatabaseUserAttributes {
126 id: string;
127}
128
129function transformIntoDatabaseSession(raw: SessionSchema): DatabaseSession {
130 const { id, user_id: userId, expires_at: expiresAtUnix, ...attributes } = raw;
131 return {
137}
138
139function transformIntoDatabaseUser(raw: UserSchema): DatabaseUser {
140 const { id, ...attributes } = raw;
141 return {