backend-plugin-api: separate out hook in addShutdownHook

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2023-02-06 15:54:19 +01:00
parent 2c68a05fd3
commit e716946103
14 changed files with 88 additions and 71 deletions
+14 -15
View File
@@ -479,10 +479,7 @@ createBackendPlugin({
// do some other stuff.
}, 1000);
lifecycle.addShutdownHook({
fn: () => clearInterval(interval),
logger,
});
lifecycle.addShutdownHook(() => clearInterval(interval));
},
});
},
@@ -499,17 +496,19 @@ The following example shows how to override the default implementation of the li
```ts
class MyCustomLifecycleService implements RootLifecycleService {
constructor(private readonly logger: LoggerService) {
['SIGKILL', 'SIGTERM'].map(signal =>
process.on(signal, () => this.shutdown()),
);
}
constructor(private readonly logger: LoggerService) {}
#isCalled = false;
#shutdownTasks: Array<LifecycleServiceShutdownHook> = [];
#shutdownTasks: Array<{
hook: LifecycleServiceShutdownHook;
options?: LifecycleServiceShutdownOptions;
}> = [];
addShutdownHook(options: LifecycleServiceShutdownHook): void {
this.#shutdownTasks.push(options);
addShutdownHook(
hook: LifecycleServiceShutdownHook,
options?: LifecycleServiceShutdownOptions,
): void {
this.#shutdownTasks.push({ hook, options });
}
async shutdown(): Promise<void> {
@@ -520,10 +519,10 @@ class MyCustomLifecycleService implements RootLifecycleService {
this.logger.info(`Running ${this.#shutdownTasks.length} shutdown tasks...`);
await Promise.all(
this.#shutdownTasks.map(async hook => {
const { logger = this.logger } = hook;
this.#shutdownTasks.map(async ({ hook, options }) => {
const logger = options?.logger ?? this.logger;
try {
await hook.fn();
await hook();
logger.info(`Shutdown hook succeeded`);
} catch (error) {
logger.error(`Shutdown hook failed, ${error}`);