11import { env } from '@/config/env'
22import type { NextFunction , Request , Response } from 'express'
3- import { IronSessionOptions } from 'iron-session'
4- import { ironSession } from 'iron-session/express'
3+ import {
4+ type SessionOptions ,
5+ type IronSession ,
6+ getIronSession
7+ } from 'iron-session'
58
6- export const SESSION_OPTIONS : IronSessionOptions = {
9+ export const SESSION_OPTIONS : SessionOptions = {
710 password : env . COOKIE_PASSWORD ,
811 cookieName : env . COOKIE_NAME ,
912 cookieOptions : {
@@ -15,8 +18,50 @@ export const SESSION_OPTIONS: IronSessionOptions = {
1518 ttl : env . COOKIE_TTL
1619} as const
1720
21+ // Utility from a previous version of iron-session.
22+ // https://github.com/vvo/iron-session/blob/v6.3.1/src/getPropertyDescriptorForReqSession.ts
23+ function getPropertyDescriptorForReqSession (
24+ session : IronSession < IronSessionData >
25+ ) : PropertyDescriptor {
26+ return {
27+ enumerable : true ,
28+ get ( ) {
29+ return session
30+ } ,
31+ set ( value ) {
32+ const keys = Object . keys ( value )
33+ const currentKeys = Object . keys ( session )
34+
35+ currentKeys . forEach ( ( key ) => {
36+ if ( ! keys . includes ( key ) ) {
37+ // @ts -expect-error unknown keys
38+ delete session [ key ]
39+ }
40+ } )
41+
42+ keys . forEach ( ( key ) => {
43+ // @ts -expect-error unknown keys
44+ session [ key ] = value [ key ]
45+ } )
46+ }
47+ }
48+ }
49+
1850export const withSession : (
1951 req : Request ,
2052 res : Response ,
2153 next : NextFunction
22- ) => Promise < void > = ironSession ( SESSION_OPTIONS )
54+ ) => Promise < void > = async ( req , res , next ) => {
55+ const session = await getIronSession < IronSessionData > (
56+ req ,
57+ res ,
58+ SESSION_OPTIONS
59+ )
60+ Object . defineProperty (
61+ req ,
62+ 'session' ,
63+ getPropertyDescriptorForReqSession ( session )
64+ )
65+
66+ next ( )
67+ }
0 commit comments