如何在 Typeorm/Typescript 中添加请求超时? [英] How to add a request timeout in Typeorm/Typescript?

查看:41
本文介绍了如何在 Typeorm/Typescript 中添加请求超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,Typeorm (Postgres) for

Today, the behavior of Typeorm (Postgres) for

  • getManager().query(...)
  • getRepositoty().createQueryBuilder(...).getMany()

是无限期地等待响应.

有没有办法引入我可能错过的请求超时?

Is there a way to introduce a request timeout that I might've missed?

如果这是不可能的,Typeorm 是否会从其池中公开连接,以便我可以实现超时机制并手动关闭数据库连接?

If this is not possible, does Typeorm expose the connection from its pool so that I can implement a timeout mechanism and close the DB connection manually?

推荐答案

要使用池中的特定连接,请使用 createQueryRunner 文档中没有关于它的信息,但它记录在api.

To work with a specific connection from the pool use createQueryRunner there is no info about it in the docs but it is documented in the api.

创建一个查询运行器,用于在单个数据库连接上执行查询.使用查询运行器,您可以控制查询以使用单个数据库连接和手动控制您的数据库事务.

Creates a query runner used for perform queries on a single database connection. Using query runners you can control your queries to execute using single database connection and manually control your database transaction.

使用示例:

const foo = <T>(callback: <T>(em: EntityManager) => Promise<T>): Promise<T> => {
    const connection = getConnection();
    const queryRunner = connection.createQueryRunner();

    return new Promise(async (resolve, reject) => {
        let res: T;
        try {
            await queryRunner.connect();
            // add logic for timeout
            res = await callback(queryRunner.manager);
        } catch (err) {
            reject(err);
        } finally {
            await queryRunner.release();
            resolve(res);
        }
    });
};

这篇关于如何在 Typeorm/Typescript 中添加请求超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆