How to add a request timeout in Typeorm/Typescript?

末鹿安然 提交于 2021-01-27 21:53:52

问题


Today, the behavior of Typeorm (Postgres) for

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

is to wait for a response indefinitely.

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

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?


回答1:


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.

Usage example:

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);
        }
    });
};




回答2:


from the documentation you can use maxQueryExecutionTime ConnectionOption.

maxQueryExecutionTime - If query execution time exceed this given max execution time (in milliseconds) then logger will log this query.

ConnectionOptions is a connection configuration you pass to createConnection or define in ormconfig



来源:https://stackoverflow.com/questions/63837096/how-to-add-a-request-timeout-in-typeorm-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!