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