session.middleware.ts 1.1 KB

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