import { Inject, Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; import * as session from 'express-session'; import * as redis from 'redis'; import { RedisStore } from 'connect-redis'; import { RedisClientType } from 'redis'; import { RedisService } from '@/shared/redis.service'; @Injectable() export class SessionMiddleware implements NestMiddleware { constructor(@Inject(RedisService) private readonly redisService: RedisService) {} use(req: Request, res: Response, next: NextFunction) { return session({ store: new RedisStore({ client: this.redisService.redisClient }), // 使用 Redis 存储 Session secret: '2129!xxxks', // 用于签名 Session ID 的密钥 resave: false, // 是否强制保存 Session saveUninitialized: false, // 是否保存未初始化的 Session cookie: { secure: false, // 如果使用 HTTPS,设置为 true maxAge: 1000 * 60 * 30, // Session 过期时间(30 分钟) }, })(req, res, next); } }