|
- import fp from 'fastify-plugin'
- import { FastifyInstance, FastifyRequest } from 'fastify'
-
- export interface FastifySessionOpts<SessionType = unknown, SessionId = string, RequestType extends FastifyRequest = FastifyRequest> {
- sessionRequestKey?: string,
- extractSessionId: (request: RequestType) => SessionId | null | undefined,
- isSessionValid: (sessionId: SessionId) => Promise<boolean>,
- getSession: (sessionId: SessionId) => Promise<SessionType>
- }
-
- const fastifySession = async (app: FastifyInstance, opts: FastifySessionOpts) => {
- const { sessionRequestKey = 'session' } = opts
- app.decorateRequest(sessionRequestKey, null)
- app.addHook('onRequest', async (request: FastifyRequest) => {
- const sessionId = opts.extractSessionId(request)
- if (typeof sessionId === 'string') {
- const isSessionValid = await opts.isSessionValid(sessionId)
- if (isSessionValid) {
- const mutableRequest = (request as unknown) as Record<string, unknown>
- mutableRequest[sessionRequestKey] = await opts.getSession(sessionId)
- }
- }
- })
- }
-
- export default fp(fastifySession)
|