From 413d7d5ce680c6537e77ad0191fe85e14e900c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20P=C3=B6hls?= Date: Sat, 4 May 2024 05:32:26 +0200 Subject: [PATCH] add shutdown callbacks to the application --- packages/application/src/application.ts | 24 ++++++++++++++++++++++++ packages/application/src/types/index.ts | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/packages/application/src/application.ts b/packages/application/src/application.ts index 3dc6c161..bc0562ed 100644 --- a/packages/application/src/application.ts +++ b/packages/application/src/application.ts @@ -55,6 +55,7 @@ export class Application extends Container implements ApplicationContract { this.meta = { appRoot: this.resolveFileURLToPath(basePath), bootingCallbacks: [], + shutdownCallbacks: [], serviceProviders: Arr.from(), packageJson: undefined, @@ -351,6 +352,27 @@ export class Application extends Container implements ApplicationContract { }) } + /** + * Returns the registered shutdown callbacks. + */ + shutdownCallbacks (): Callback[] { + return this.meta.shutdownCallbacks + } + + /** + * Register a shutdown callback that runs after all service provides ran + * their `shutdown` function. + */ + onShutdown (callback: Callback): this { + if (typeof callback !== 'function') { + throw new Error(`You must pass a function to the application’s "onShutdown" function. Received [${String(callback)}]`) + } + + return tap(this, () => { + this.meta.shutdownCallbacks.push(callback) + }) + } + /** * Register the configured user-land providers. */ @@ -457,6 +479,8 @@ export class Application extends Container implements ApplicationContract { ).forEach(async provider => { await this.shutdownProvider(provider) }) + + await this.runAppCallbacks(this.shutdownCallbacks()) } /** diff --git a/packages/application/src/types/index.ts b/packages/application/src/types/index.ts index ea2b3fe3..0d5a3097 100644 --- a/packages/application/src/types/index.ts +++ b/packages/application/src/types/index.ts @@ -41,6 +41,12 @@ export interface ApplicationMeta { */ bootingCallbacks: Callback[] + /** + * Shutdown callbacks run when the application stops. We’re + * using this in the framework to u + */ + shutdownCallbacks: Callback[] + /** * All registered service providers. */