Root Lifecycle 서비스
이 서비스는 lifecycle 서비스와 같지만, root 서비스에서만 사용해야 해요. 실제 lifecycle 훅에 대한 구현이 모여서 실행되는 곳이기도 해요. 그래서 그 훅들이 처리되는 방식의 구현을 덮어쓰고 싶다면 이 서비스를 덮어써야 해요.
출처: 문서
본문
이 서비스는 lifecycle 서비스와 같지만, root 서비스에서만 사용해야 해요. 실제 lifecycle 훅에 대한 구현이 모여서 실행되는 곳이기도 해요. 그래서 그 훅들이 처리되는 방식의 구현을 덮어쓰고 싶다면 이 서비스를 덮어써야 해요.
서비스 구성하기
다음 예시는 lifecycle 서비스의 기본 구현을, 원래와 다른 프로세스 이벤트를 수신하는 구현으로 덮어쓰는 방법을 보여줘요.
class MyCustomLifecycleService implements RootLifecycleService {
constructor(private readonly logger: LoggerService) {}
#isCalled = false;
#shutdownTasks: Array<{
hook: LifecycleServiceShutdownHook;
options?: LifecycleServiceShutdownOptions;
}> = [];
addShutdownHook(
hook: LifecycleServiceShutdownHook,
options?: LifecycleServiceShutdownOptions,
): void {
this.#shutdownTasks.push({ hook, options });
}
async shutdown(): Promise<void> {
if (this.#isCalled) {
return;
}
this.#isCalled = true;
this.logger.info(`Running ${this.#shutdownTasks.length} shutdown tasks...`);
await Promise.all(
this.#shutdownTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook();
logger.info(`Shutdown hook succeeded`);
} catch (error) {
logger.error(`Shutdown hook failed, ${error}`);
}
}),
);
}
}
const backend = createBackend();
backend.add(
createServiceFactory({
service: coreServices.rootLifecycle,
deps: {
logger: coreServices.rootLogger,
},
async factory({ logger }) {
return new MyCustomLifecycleService(logger);
},
}),
);