使用 Typescript Express mysql 会话存储

Express mysql session store with Typescript

我正在尝试使用 Typescript 在 NestJS 中创建一个 mysql 会话存储。我已经安装了 express-session、express-mysql-session 和 @types/express-mysql-session 包。下面的代码编译(main.ts 文件),但控制台中出现错误:

import { AppModule } from "./app.module";
import { env } from "./common/env";
import session from "express-session";
import MySQLStore from "express-mysql-session";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: { credentials: env.ENABLE_CORS, origin: env.CLIENT_HOST },
  });

  //session store
  const options = {
    host: "db",
    port: 3306,
    user: env.DB_USER,
    password: env.DB_PASSWD,
    database: env.DATABASE,
    checkExpirationInterval: 1000 * 60 * 60 * 2,
    expiration: 1000 * 60 * 60 * 24,
  };

  const store = MySQLStore(session);
  const sessionStore = new store(options);

  app.use(
    session({
      secret: env.COOKIE_SECRET,
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24,
      },
    }),
  );

  await app.listen(env.PORT_BACKEND || 8080);
}
bootstrap();

错误是 picture here

使用 require 而不是 import 甚至无法编译,我已经尝试过 express-mysql-session 包方式:

var MySQLStore = require('express-mysql-session')(session);

我应该如何让它发挥作用?或者还有其他更好的套餐吗?

好的,所以我成功了。最后还安装了 mysql2 包,您可以阅读 为什么。

代码最终是这样的:

import { NestFactory } from "@nestjs/core";
import { env } from "./common/env";
import { AppModule } from "./modules/app/app.module";
import * as session from "express-session";
import * as MySQLStoreCreator from "express-mysql-session";
import * as mysql2 from "mysql2/promise";

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    cors: { credentials: env.ENABLE_CORS, origin: env.CLIENT_HOST },
  });

  //session store
  const options = {
    host: "db",
    port: 3306,
    user: env.DB_USER,
    password: env.DB_PASSWD,
    database: env.DATABASE,
    checkExpirationInterval: 1000 * 60 * 60 * 2,
    expiration: 1000 * 60 * 60 * 24,
  };

  const connection = mysql2.createPool(options);
  const sessionStore = new (MySQLStoreCreator(session))({}, connection);

  app.use(
    session({
      secret: env.COOKIE_SECRET,
      store: sessionStore,
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24,
      },
    }),
  );

  await app.listen(env.PORT_BACKEND || 8080);
}
bootstrap();

也许有人会觉得有用 C: