如何使用 Redis 作为 Express Session NestJS 的存储

How to use Redis as a store for Express Session NestJS

我正在使用 NestJS 创建一个 API 并试图为我的快速会话设置一个会话存储,但我从这一行收到错误。我确实在我创建的一个新项目中使用了 express-session 和 Redis,我只是事先使用 express 来了解 Redis 和 express session 是如何工作的,但是当我尝试将它移植到 NestJS 时它没有工作。

Main.ts

import connectRedis from 'connect-redis';
import { redis } from './redis';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const RedisStore = connectRedis(session);

这是我得到的错误

const RedisStore = connectRedis(session);
                               ^
TypeError: connect_redis_1.default is not a function

错误发生在任何其他与 redis 相关的功能或调用 express-session 之前。我仍然会包括我如何设置 Redis 和 Express-Session 以备不时之需。

Redis.ts

import Redis from 'ioredis';

export const redis = new Redis(
  port,
  'hostName',
  { password: 'password' },
);

Main.ts

内的会话
  app.use(
    session({
      store: new RedisStore({ client: redis }),
      cookie: {
        maxAge: 60000 * 60 * 24,
      },
      secret: 'mysecret',
      saveUninitialized: false,
      resave: false,
    }),
  );

我确实从 NestJS 文档中读到我可以将 Redis 设置为微服务,但是我真的只需要 Redis 用于我的 Express-Session,如果我能解决这个问题,我不想设置 Redis 微服务。

我还使用 Mongoose 连接到我的 MongoDB,我将其用于 NestJS 内部的存储库。以前在其他项目中而不是使用 Redis 我会使用 ORMSession 在 TypeORM 中设置我的商店,如果有人有与 Mongoose 一起使用的替代方案那么那也可以。

const sessionRepo = getRepository(TypeORMSession);

...

store: new TypeormStore().connect(sessionRepo),

错误说明就在那里。 connect_redis1.default 不是函数。相反,您应该使用 import * as conectRedis from 'connect-redis'I've got an example here 看起来像这样:

import { Inject, Logger, MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import * as RedisStore from 'connect-redis';
import * as session from 'express-session';
import { session as passportSession, initialize as passportInitialize } from 'passport';
import { RedisClient } from 'redis';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth';
import { REDIS, RedisModule } from './redis';

@Module({
  imports: [AuthModule, RedisModule],
  providers: [AppService, Logger],
  controllers: [AppController],
})
export class AppModule implements NestModule {
  constructor(@Inject(REDIS) private readonly redis: RedisClient) {}
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(
        session({
          store: new (RedisStore(session))({ client: this.redis, logErrors: true }),
          saveUninitialized: false,
          secret: 'sup3rs3cr3t',
          resave: false,
          cookie: {
            sameSite: true,
            httpOnly: false,
            maxAge: 60000,
          },
        }),
        passportInitialize(),
        passportSession(),
      )
      .forRoutes('*');
  }
}

您需要安装@types/connect-redis

并做

从 'connect-redis' 导入 * 作为 _connectRedis;