|
| 1 | +import type { IncomingMessage, ServerResponse } from 'http'; |
| 2 | + |
| 3 | +import type { IronSessionOptions } from 'iron-session'; |
| 4 | +import { getIronSession } from 'iron-session/edge'; |
| 5 | +import type { |
| 6 | + NextApiHandler, |
| 7 | + GetServerSidePropsContext, |
| 8 | + GetServerSidePropsResult, |
| 9 | + NextApiRequest, |
| 10 | + NextApiResponse, |
| 11 | +} from 'next'; |
| 12 | + |
| 13 | +import getPropertyDescriptorForRequestSession from './get-property-descriptor-for-request-session'; |
| 14 | + |
| 15 | +// Argument types based on getIronSession function |
| 16 | +type GetIronSessionApiOptions = ( |
| 17 | + request: NextApiRequest, |
| 18 | + response: NextApiResponse |
| 19 | +) => Promise<IronSessionOptions> | IronSessionOptions; |
| 20 | + |
| 21 | +export function withIronSessionApiRoute( |
| 22 | + handler: NextApiHandler, |
| 23 | + options: IronSessionOptions | GetIronSessionApiOptions |
| 24 | +): NextApiHandler { |
| 25 | + return async (request, response) => { |
| 26 | + const sessionOptions = options instanceof Function ? await options(request, response) : options; |
| 27 | + const session = await getIronSession(request, response, sessionOptions); |
| 28 | + |
| 29 | + // We define req.session as being enumerable (so console.log(req) shows it) |
| 30 | + // and we also want to allow people to do: |
| 31 | + // req.session = { admin: true }; or req.session = {...req.session, admin: true}; |
| 32 | + // req.session.save(); |
| 33 | + // eslint-disable-next-line @silverhand/fp/no-mutating-methods |
| 34 | + Object.defineProperty(request, 'session', getPropertyDescriptorForRequestSession(session)); |
| 35 | + |
| 36 | + return handler(request, response); |
| 37 | + }; |
| 38 | +} |
| 39 | + |
| 40 | +// Argument type based on the SSR context |
| 41 | +type GetIronSessionSsrOptions = ( |
| 42 | + request: IncomingMessage, |
| 43 | + response: ServerResponse |
| 44 | +) => Promise<IronSessionOptions> | IronSessionOptions; |
| 45 | + |
| 46 | +export function withIronSessionSsr<P extends Record<string, unknown> = Record<string, unknown>>( |
| 47 | + handler: ( |
| 48 | + context: GetServerSidePropsContext |
| 49 | + ) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>, |
| 50 | + options: IronSessionOptions | GetIronSessionSsrOptions |
| 51 | +) { |
| 52 | + return async (context: GetServerSidePropsContext) => { |
| 53 | + const sessionOptions = |
| 54 | + options instanceof Function ? await options(context.req, context.res) : options; |
| 55 | + const session = await getIronSession(context.req, context.res, sessionOptions); |
| 56 | + |
| 57 | + // eslint-disable-next-line @silverhand/fp/no-mutating-methods |
| 58 | + Object.defineProperty(context.req, 'session', getPropertyDescriptorForRequestSession(session)); |
| 59 | + |
| 60 | + return handler(context); |
| 61 | + }; |
| 62 | +} |
0 commit comments