0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NestJS + TypeORMでSQLタイムアウトを設定

Posted at

NestJS + TypeORMでSQLタイムアウトを設定

NestJS + TypeORMでSQLタイムアウトを設定するには、TypeORMのデータベース接続オプションでタイムアウト値を指定します。

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql', // または 'postgres'
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'test',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
      // タイムアウト設定(MySQL/MariaDBの場合)
      connectTimeout: 10000, // 接続タイムアウト(ミリ秒)
      // クエリタイムアウト(MySQLはサポートしていませんが、PostgreSQLは下記のように設定可能)
      // statement_timeout: 10000, // PostgreSQLの場合(ミリ秒)
    }),
  ],
})
export class AppModule {}

2. PostgreSQLでクエリタイムアウトを設定する場合


TypeOrmModule.forRoot({
  type: 'postgres',
  // ......
  statement_timeout: 10000, // クエリタイムアウト(ミリ秒)
}),

リポジトリで個別にタイムアウトを設定したい場合

TypeORM自体はクエリごとのタイムアウトを直接サポートしていませんが、
クエリランナーを使って生SQLでタイムアウトを設定することは可能です(PostgreSQLの場合)。

// 任意のサービスやリポジトリ内
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private dataSource: DataSource,
  ) {}

  async findWithTimeout() {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    // クエリタイムアウトを設定(PostgreSQL)
    await queryRunner.query('SET statement_timeout TO 5000');
    const result = await queryRunner.query('SELECT * FROM user');
    await queryRunner.release();
    return result;
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?