TypeORM 全局创建连接

Nab*_*eel 3 node.js typescript typeorm

我在用 在我的节点 Js 应用程序中typeormtypescript。我试图找出为类中的所有函数使用单个数据库连接的方法。例如,我的类有两个函数,并且希望对所有函数使用全局/单个连接,而不是在每个函数中创建一个连接,如下所示:

export class SQLDBService implements IDatabaseService{
private readonly logger = getLogger("SQLDBService");
private connection:Connection;


  getConversation(conversationId: string): ConversationEntity {

    let conversationEntity = new ConversationEntity();
    createConnection(/*...*/).then(async connection => {
        let dbObj = await connection.getRepository(ConversationEntity).findOne({
            conversationId: Equal(conversationId)
        });
        if(dbObj)
            conversationEntity = dbObj;
    });
    return conversationEntity;
}

  pushWrapUp(conversationId: string, wrapUp: string): void {

    createConnection().then(async connection => {
        let conversationEntity = await connection.getRepository(ConversationEntity).findOne({
            conversationId: Equal(conversationId)
        });
        if(conversationEntity){
            conversationEntity.wrapUp = wrapUp;
            conversationEntity.endTime = new Date();
            await connection.manager.save(conversationEntity);
        }
    });
}}
Run Code Online (Sandbox Code Playgroud)

有人可以指出我正确的方向吗?

Est*_*ask 5

上面的代码不能有效地使用,async..await因为 promise 没有被链接,这会导致错误处理和控制流不正确。

正如文档所解释的那样,

TypeORM 的 Connection 并没有像看起来那样设置数据库连接,而是设置了一个连接池。<...> 一旦调用 Connection 的 connect 方法,就会建立连接池设置。如果您使用 createConnection 函数设置连接,则会自动调用 connect 方法。调用 close 时会断开连接(关闭池中的所有连接)。通常,您必须在应用程序引导程序中只创建一次连接,并在完全完成对数据库的操作后关闭它。

createConnection应该在应用程序初始化时只调用一次。由于它是异步的,初始化例程应该在使用 TypeORM 模型之前等待它。

正如文档所建议的,getConnection()可以使用 代替createConnection. 由于目的是获取默认连接的存储库,getRepository因此可以改用:

它的:

import {getRepository} from "typeorm";

  ...
  async getConversation(conversationId: string): ConversationEntity {
    let conversationEntity = new ConversationEntity();
    let dbObj = getRepository(ConversationEntity).findOne({
      conversationId: Equal(conversationId)
    });
    if(dbObj) conversationEntity = dbObj;
    return conversationEntity;
  }
Run Code Online (Sandbox Code Playgroud)