Essentials
Hooks & lifecycle
Some work has to happen at a specific moment, not in response to a request: open a pool at startup, flush it at shutdown, observe every event as it passes. Hooks give you those moments by name, so that code lives where it belongs instead of leaking into handlers.
#Declaring a hook
Mark a method with @Hook(name). The kernel calls it at the matching moment, with the app's dependencies available. Startup and shutdown hooks fire once; per-event hooks fire inside each ephemeral container.
import { Hook, StoneApp } from '@stone-js/core'
@StoneApp({ name: 'tasks' })
export class Application {
@Hook('onStart')
async warmUp ({ container }) {
await container.resolve('db').connect() // once, at startup
}
@Hook('onTerminate')
async drain ({ container }) {
await container.resolve('db').close() // once, at shutdown
}
}#The lifecycle moments
| Hook | Type | Description |
|---|---|---|
| onInit | process | The app is being initialised, before it starts. |
| onStart | process | The app has started; warm long-lived resources here. |
| onHandlingEvent | per event | An event is about to be handled. |
| onExecutingEventHandler | per event | The handler is about to run. |
| onExecutingErrorHandler | per event | An error handler is about to run. |
| onStop | process | The app is stopping. |
| onTerminate | process | Final teardown; flush and close. |
#Imperative hooks
import { defineHookListener } from '@stone-js/core'
export const hooks = [
defineHookListener('onStart', ({ container }) => container.resolve('db').connect())
]