/
prisma-session-store.ts
executable file
·470 lines (408 loc) · 12.6 KB
/
prisma-session-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import cuid from 'cuid';
import { SessionData, Store } from 'express-session';
import { dedent } from 'ts-dedent';
import type { PartialDeep } from 'type-fest';
import type { IOptions, IPrisma, ISessions } from '../@types';
import { ManagedLogger } from './logger';
import { createExpiration, defer, getTTL } from './utils';
/**
* An `express-session` store used in the `express-session` options
* to hook up prisma as a session store
*
* @example
* ```ts
* const app = express();
* const prisma = new PrismaClient();
*
* app.use(
* expressSession({
* secret: "Some Secret Value",
* resave: false,
* saveUninitialized: false,
* store: new PrismaSessionStore(prisma, {
* checkPeriod: 10 * 60 * 1000 // 10 minutes
* });
* })
* );
* ```
*/
export class PrismaSessionStore extends Store {
/**
* Initialize PrismaSessionStore with the given `prisma` and (optional) `options`.
*
* @param prisma the prisma client that includes a `Sessions` model
* @param options the options to alter how this store behaves
*
* @example
* ```ts
* const app = express();
* const prisma = new PrismaClient();
*
* app.use(
* expressSession({
* secret: "Some Secret Value",
* resave: false,
* saveUninitialized: false,
* store: new PrismaSessionStore(prisma, {
* checkPeriod: 10 * 60 * 1000 // 10 minutes
* });
* })
* );
* ```
*/
constructor(
private readonly prisma: IPrisma,
private readonly options: IOptions
) {
super();
this.startInterval();
this.connect();
}
/**
* @description The currently active interval created with `startInterval()` and removed with `stopInterval()`
*/
private checkInterval?: NodeJS.Timeout;
/**
* @description A flag indicating to use the session ID as the Prisma Record ID
*
* Note: If undefined and dbRecordIdFunction is also undefined then a random
* CUID will be used instead.
*/
private readonly dbRecordIdIsSessionId = this.options.dbRecordIdIsSessionId;
/**
* @description whether or not the prisma connection has been tested to be invalid
*/
private invalidConnection = false;
/**
* @description A object that handles logging to a given logger based on the logging level
*/
private readonly logger = new ManagedLogger(
this.options.logger ?? console,
this.options.loggerLevel ?? ['error']
);
/**
* @description Some serializer that will transform objects into strings
* and vice versa
*/
private readonly serializer = this.options.serializer ?? JSON;
/**
* Attempts to connect to Prisma, displaying a pretty error if the connection is not possible.
*/
private async connect(): Promise<void> {
await this.prisma?.$connect?.();
await this.validateConnection();
}
/**
* @description A function to generate the Prisma Record ID for a given session ID
*
* Note: If undefined and dbRecordIdIsSessionId is also undefined then a random
* CUID will be used instead.
*/
private readonly dbRecordIdFunction = (sid: string) =>
this.options.dbRecordIdFunction?.(sid) ?? cuid();
/**
* Disables store, used when prisma cannot be connected to
*/
private disable(): void {
this.invalidConnection = true;
}
/**
* Returns if the connect is valid or not, logging an error if it is not.
*/
private async validateConnection(): Promise<boolean> {
await (
this.prisma?.$connect?.() ??
Promise.reject(new Error('Could not connect'))
).catch(() => {
this.disable();
this.stopInterval();
this.logger.error(dedent`Could not connect to Sessions model in Prisma.
Please make sure that prisma is setup correctly and that your migrations are current.
For more information check out https://github.com/kleydon/prisma-session-store`);
});
return !this.invalidConnection;
}
/**
* Fetch all sessions
*
* @param callback a callback providing all session data
* or an error that occurred
*/
public readonly all = async (
callback?: (err?: unknown, all?: ISessions) => void
) => {
if (!(await this.validateConnection())) return callback?.();
try {
const sessions = await this.prisma.session.findMany({
select: { sid: true, data: true },
});
const result = sessions
.map(
({ sid, data }) =>
[sid, this.serializer.parse(data ?? '{}') as SessionData] as const
)
.reduce<ISessions>(
(prev, [sid, data]) => ({ ...prev, [sid]: data }),
{}
);
if (callback) defer(callback, undefined, result);
return result;
} catch (e: unknown) {
this.logger.error(`all(): ${String(e)}`);
if (callback) defer(callback, e);
}
};
/**
* Delete all sessions from the store
*
* @param callback a callback notifying that all sessions
* were deleted or that an error occurred
*/
public readonly clear = async (callback?: (err?: unknown) => void) => {
if (!(await this.validateConnection())) return callback?.();
try {
await this.prisma.session.deleteMany();
if (callback) defer(callback);
} catch (e: unknown) {
if (callback) defer(callback, e);
}
};
/**
* Destroy the session(s) associated with the given `sid`(s).
*
* @param sid a single or multiple id(s) to remove data for
* @param callback a callback notifying that the session(s) have
* been destroyed or that an error occurred
*/
public readonly destroy = async (
sid: string | string[],
callback?: (err?: unknown) => void
) => {
if (!(await this.validateConnection())) return callback?.();
try {
if (Array.isArray(sid)) {
await Promise.all(sid.map(async (s) => this.destroy(s, callback)));
} else {
await this.prisma.session.delete({ where: { sid } });
}
} catch (e: unknown) {
this.logger.warn(
`Attempt to destroy non-existent session:${String(sid)} ${String(e)}`
);
if (callback) defer(callback, e);
}
if (callback) defer(callback);
};
/**
* Attempt to fetch session by the given `sid`.
*
* @param sid the sid to attempt to fetch
* @param callback a function to call with the results
*/
public readonly get = async (
sid: string,
callback?: (err?: unknown, val?: SessionData) => void
) => {
if (!(await this.validateConnection())) return callback?.();
const session = await this.prisma.session
.findUnique({
where: { sid },
})
.catch(() => null);
if (session === null) return callback?.();
try {
const result = this.serializer.parse(session.data ?? '{}') as SessionData;
if (callback) defer(callback, undefined, result);
return result;
} catch (e: unknown) {
this.logger.error(`get(): ${String(e)}`);
if (callback) defer(callback, e);
}
};
/**
* Fetch all sessions' ids
*
* @param callback a callback providing all session id
* or an error that occurred
*/
public readonly ids = async (
callback?: (err?: unknown, ids?: number[]) => void
) => {
if (!(await this.validateConnection())) return callback?.();
// XXX More efficient way? XXX
try {
const sessions = await this.prisma.session.findMany({
select: { sid: true },
});
const sids = sessions.map(({ sid }) => sid);
if (callback) defer(callback, undefined, sids);
return sids;
} catch (e: unknown) {
if (callback) defer(callback, e);
}
};
/**
* Get the count of all sessions in the store
*
* @param callback a callback providing either the number of sessions
* or an error that occurred
*/
public readonly length = async (
callback?: (err: unknown, length: number) => void
) => {
if (!(await this.validateConnection()))
return callback?.(new Error('Could not connect'), 0);
// XXX More efficient way? XXX
try {
const sessions = await this.prisma.session.findMany({
select: { sid: true }, // Limit what gets sent back; can't be empty.
});
const itemCount = sessions.length;
if (callback) defer(callback, undefined, itemCount);
return itemCount;
} catch (e: unknown) {
if (callback) defer(callback, e);
}
};
/**
* Remove only expired entries from the store
*/
public readonly prune = async () => {
if (!(await this.validateConnection())) return;
// XXX More efficient way? Maybe when filtering is fully implemented? XXX
this.logger.log('Checking for any expired sessions...');
const sessions = await this.prisma.session.findMany({
select: {
expiresAt: true,
sid: true,
},
});
for (const session of sessions) {
const now = new Date();
const remainingSec = (session.expiresAt.valueOf() - now.valueOf()) / 1000;
this.logger.log(`session:${session.sid} expires in ${remainingSec}sec`);
if (now.valueOf() >= session.expiresAt.valueOf()) {
this.logger.log(`Deleting session with sid: ${session.sid}`);
await this.prisma.session.delete({
where: { sid: session.sid },
});
}
}
};
/**
* Commit the given `session` object associated with the given `sid`.
*
* @param sid the ID to save the session data under
* @param session the session data to save
* @param callback a callback with the results of saving the data
* or an error that occurred
*/
public readonly set = async (
sid: string,
session: PartialDeep<SessionData>,
callback?: (err?: unknown) => void
) => {
if (!(await this.validateConnection())) return callback?.();
const ttl = getTTL(this.options, session, sid);
const expiresAt = createExpiration(ttl, {
rounding: this.options.roundTTL,
});
let sessionString;
try {
sessionString = this.serializer.stringify(session);
} catch (e: unknown) {
this.logger.error(`set(): ${String(e)}`);
if (callback) defer(callback, e);
return;
}
const existingSession = await this.prisma.session
.findUnique({
where: { sid },
})
.catch(() => null);
const data = {
sid,
expiresAt,
data: sessionString,
id: this.dbRecordIdIsSessionId ? sid : this.dbRecordIdFunction(sid),
};
if (existingSession !== null) {
await this.prisma.session.update({
data,
where: { sid },
});
} else {
await this.prisma.session.create({
data: { ...data, data: sessionString },
});
}
if (callback) defer(callback);
};
/**
* A function to stop any ongoing intervals and disconnect from the `PrismaClient`
*/
public async shutdown(): Promise<void> {
this.stopInterval();
await this.prisma.$disconnect();
}
/**
* Start an interval to prune expired sessions
*/
public startInterval(): void {
const ms = this.options.checkPeriod;
if (typeof ms === 'number' && ms !== 0) {
this.stopInterval();
this.checkInterval = setInterval(() => {
this.prune();
}, Math.floor(ms));
}
}
/**
* Stop checking if sessions have expired
*/
public stopInterval(): void {
if (this.checkInterval) clearInterval(this.checkInterval);
}
/**
* Refresh the time-to-live for the session with the given `sid`.
*
* @param sid the id of the session to refresh
* @param session the data of the session to resave
* @param callback a callback notifying that the refresh was completed
* or that an error occurred
*/
public readonly touch = async (
sid: string,
session: PartialDeep<SessionData>,
callback?: (err?: unknown) => void
) => {
if (!(await this.validateConnection())) return callback?.();
const ttl = getTTL(this.options, session, sid);
const expiresAt = createExpiration(ttl, {
rounding: this.options.roundTTL,
});
try {
const existingSession = await this.prisma.session.findUnique({
where: { sid },
});
if (existingSession !== null) {
const existingSessionData = {
...this.serializer.parse(existingSession.data ?? '{}'),
cookie: session.cookie,
};
await this.prisma.session.update({
where: { sid: existingSession.sid },
data: {
expiresAt,
data: this.serializer.stringify(existingSessionData),
},
});
}
// *** If there is no found session, for some reason, should it be recreated from sess *** ?
if (callback) defer(callback);
} catch (e: unknown) {
this.logger.error(`touch(): ${String(e)}`);
if (callback) defer(callback, e);
}
};
}