Web API for code.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

27 lines
1.0 KiB

  1. import fp from 'fastify-plugin'
  2. import { FastifyInstance, FastifyRequest } from 'fastify'
  3. export interface FastifySessionOpts<SessionType = unknown, SessionId = string, RequestType extends FastifyRequest = FastifyRequest> {
  4. sessionRequestKey?: string,
  5. extractSessionId: (request: RequestType) => SessionId | null | undefined,
  6. isSessionValid: (sessionId: SessionId) => Promise<boolean>,
  7. getSession: (sessionId: SessionId) => Promise<SessionType>
  8. }
  9. const fastifySession = async (app: FastifyInstance, opts: FastifySessionOpts) => {
  10. const { sessionRequestKey = 'session' } = opts
  11. app.decorateRequest(sessionRequestKey, null)
  12. app.addHook('onRequest', async (request: FastifyRequest) => {
  13. const sessionId = opts.extractSessionId(request)
  14. if (typeof sessionId === 'string') {
  15. const isSessionValid = await opts.isSessionValid(sessionId)
  16. if (isSessionValid) {
  17. const mutableRequest = (request as unknown) as Record<string, unknown>
  18. mutableRequest[sessionRequestKey] = await opts.getSession(sessionId)
  19. }
  20. }
  21. })
  22. }
  23. export default fp(fastifySession)