50 lines
1.4 KiB
TypeScript
50 lines
1.4 KiB
TypeScript
import {
|
|
Inject,
|
|
Injectable,
|
|
OnModuleDestroy,
|
|
OnModuleInit,
|
|
} from '@nestjs/common';
|
|
import { PrismaPg } from '@prisma/adapter-pg';
|
|
import { PrismaClient } from '../generated/prisma/client';
|
|
import { ENVIRONMENT } from '../config/environment.module';
|
|
import type { Environment } from '../config/environment';
|
|
|
|
export function utcDatabaseUrl(value: string, fallbackOptions = '') {
|
|
const url = new URL(value);
|
|
const options = url.searchParams.get('options') || fallbackOptions;
|
|
url.searchParams.set('options', `${options} -c timezone=UTC`.trim());
|
|
return url.toString();
|
|
}
|
|
|
|
@Injectable()
|
|
export class DatabaseService
|
|
extends PrismaClient
|
|
implements OnModuleInit, OnModuleDestroy
|
|
{
|
|
constructor(@Inject(ENVIRONMENT) environment: Environment) {
|
|
// The installed adapter serializes UTC wall-clock values without offsets.
|
|
// Enforce UTC on every pooled connection, preserving other startup options.
|
|
super({
|
|
adapter: new PrismaPg({
|
|
connectionString: utcDatabaseUrl(
|
|
environment.DATABASE_URL,
|
|
process.env.PGOPTIONS ?? '',
|
|
),
|
|
connectionTimeoutMillis: 3000,
|
|
query_timeout: 3000,
|
|
max: environment.DATABASE_POOL_SIZE,
|
|
}),
|
|
});
|
|
}
|
|
|
|
async onModuleInit(): Promise<void> {
|
|
await this.$connect();
|
|
}
|
|
async onModuleDestroy(): Promise<void> {
|
|
await this.$disconnect();
|
|
}
|
|
async ping(): Promise<void> {
|
|
await this.$queryRaw`SELECT 1`;
|
|
}
|
|
}
|