Hooks
Hooks are a way to tap into the lifecycle of a class, and perform actions at specific points in time. They are implemented as decorators, and can be used on any class that is managed by the Sodacore framework, such as controllers, services, providers, etc.
Available Hooks
There are a variety of hooks available, but it's worth noting that each plugin may expose and dispatch their own hooks.
Core Hooks
preInit
- Called before the init stage.postInit
- Called after the init stage.preStart
- Called before the start stage.postStart
- Called after the start stage.preStop
- Called before the stop stage.postStop
- Called after the stop stage.
Be aware that
preStop
andpostStop
are called when the application is shutting down, but be aware that the way Node/Bun works, sometimes the process will stop before everything has been completed, so don't rely on these hooks for anything critical.
HTTP Hooks
httpRequest
- Called when an HTTP request is received, before any routing or middlewares have fired.sseRequest
- Called when an SSE request is received, before any routing or middlewares have fired.
WebSocket Hooks
wsOpen
- Called when a WebSocket connection is opened.wsClose
- Called when a WebSocket connection is closed.wsDrain
- Called when a WebSocket connection is drained.
Usage
To use a hook, simply import the Hook
decorator and wrap any method within your class, for example:
import { Controller, Get } from '@sodacore/http';
import { Hook } from '@sodacore/core';
@Controller('/users')
export class UserController {
@Hook('httpRequest')
public onRequest() {
console.log('HTTP request received');
}
@Get('/')
async getUsers() {
// ...
}
}
Note: Hooks can be given contextual data, but this can be different depending on the hook, we urge you to actually console log the outputs of the hooks to see what data is available to you, for example, the
httpRequest
hook will give you the request, response and server objects, so you can manipulate them as you see fit.
This behaviour is documented and used within the Demo project, here where it's used to update a connection count property and then broadcasted to all clients.