我在typescript对象中使用TypeOrm
来创建数据库连接:https://typeorm.io/#/connection-api。我直接使用连接API,而不是管理器。问题是,如果我在第二次重新创建数据库连接,它将抛出一个异常:
await createConnection(params);
AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session
我需要重新创建的原因是使用不同的凭据来创建连接。
如何重新创建连接?
如果您正在使用基于express的nodejs应用程序,并且希望使用中间件与任何类型的数据库进行TypeOrm连接。然后在中间件文件中使用以下代码。
中间件。ts
import * as express from express';
import (createConnection, getConnectionManager) from "typeorm":
export const dbConnection async (req:express.Request,
res:express.Response, next: express.NextFunction) => {
if(!getConnectionManager().has("default")) {
await createConnection();
}
next();
}
ln索引。ts在行下方添加
import {dbConnection} from '/.middleware.ts';
import * as express from 'express';
const app = express () ;
app.use(dbConnection) ;