sharkey/packages/backend/src/GlobalModule.ts

76 lines
2.1 KiB
TypeScript
Raw Normal View History

import { setTimeout } from 'node:timers/promises';
2022-09-18 03:27:08 +09:00
import { Global, Inject, Module } from '@nestjs/common';
2022-09-21 04:54:21 +09:00
import Redis from 'ioredis';
2022-09-18 03:27:08 +09:00
import { DataSource } from 'typeorm';
import { createRedisConnection } from '@/redis.js';
import { DI } from './di-symbols.js';
import { loadConfig } from './config.js';
2023-02-07 19:50:38 +09:00
import { createPostgresDataSource } from './postgres.js';
import { RepositoryModule } from './models/RepositoryModule.js';
2022-09-18 03:27:08 +09:00
import type { Provider, OnApplicationShutdown } from '@nestjs/common';
const config = loadConfig();
const $config: Provider = {
provide: DI.config,
useValue: config,
};
const $db: Provider = {
provide: DI.db,
2022-09-22 05:11:26 +09:00
useFactory: async (config) => {
2023-02-07 19:50:38 +09:00
const db = createPostgresDataSource(config);
2022-09-18 03:27:08 +09:00
return await db.initialize();
},
2022-09-22 05:11:26 +09:00
inject: [DI.config],
2022-09-18 03:27:08 +09:00
};
const $redis: Provider = {
provide: DI.redis,
2022-09-22 05:11:26 +09:00
useFactory: (config) => {
const redisClient = createRedisConnection(config);
2022-09-18 03:27:08 +09:00
return redisClient;
},
2022-09-22 05:11:26 +09:00
inject: [DI.config],
2022-09-18 03:27:08 +09:00
};
const $redisSubscriber: Provider = {
provide: DI.redisSubscriber,
2022-09-22 05:11:26 +09:00
useFactory: (config) => {
const redisSubscriber = createRedisConnection(config);
2022-09-18 03:27:08 +09:00
redisSubscriber.subscribe(config.host);
return redisSubscriber;
},
2022-09-22 05:11:26 +09:00
inject: [DI.config],
2022-09-18 03:27:08 +09:00
};
@Global()
@Module({
imports: [RepositoryModule],
providers: [$config, $db, $redis, $redisSubscriber],
exports: [$config, $db, $redis, $redisSubscriber, RepositoryModule],
})
export class GlobalModule implements OnApplicationShutdown {
constructor(
@Inject(DI.db) private db: DataSource,
2022-09-21 04:54:21 +09:00
@Inject(DI.redis) private redisClient: Redis.Redis,
@Inject(DI.redisSubscriber) private redisSubscriber: Redis.Redis,
2022-09-18 03:27:08 +09:00
) {}
async onApplicationShutdown(signal: string): Promise<void> {
if (process.env.NODE_ENV === 'test') {
// XXX:
// Shutting down the existing connections causes errors on Jest as
// Misskey has asynchronous postgres/redis connections that are not
// awaited.
// Let's wait for some random time for them to finish.
await setTimeout(5000);
}
2022-09-18 03:27:08 +09:00
await Promise.all([
this.db.destroy(),
this.redisClient.disconnect(),
this.redisSubscriber.disconnect(),
]);
}
}