Lifecycle and Hooks
Lifecycle in Frourio
Both frourio and frourio-express provide hooks that take a form similar to fastify.
The overall lifecycle is shown in the figure below, and hooks such as onRequest
, preParsing
, preValidation
, and preHandler
can be defined.
Ref. Lifecycle - Fastify
Two Types of Hooks
Frourio provides two types of hooks: controller-level hooks and directory-level hooks.
- Controller-level Hooks: called at the current endpoints.
- Directory-level Hooks: called at the current and subordinate endpoints.
If both hooks are to be called, Directory-level Hooks is called first.
Define Hooks
To define hooks, use the function defineHooks
exported by ./$relay.ts
.
- Controller-level Hooks: define in
controller.ts
. - Directory-level Hooks: define in
hooks.ts
at the top of the target directory.
Function defineHooks
- Fastify
- Express
Argument Type
- function
(fastify: FastifyInstance) => Hooks
Hooks
: An object having the hooks name as keys and the handler functions (or its array) as values.
Hooks Handler
Argument Type
request
:FastifyRequest
&AdditinalRequest
reply
:FastifyReply
done
: function<TError extends Error = FastifyError>(err?: TError) => void
done
is the function to continue with the lifecycle.
The done
callback is not available when using async
/await
or returning a Promise
. If you do invoke a done callback in this situation unexpected behavior may occur, e.g. duplicate invocation of handlers.
ref. Hooks - Fastify
Argument Type
- function
(app: Express) => Hooks
Hooks
: An object having the hooks name as keys and the handler functions (or its array) as values.
Hooks Handler
Argument Type
req
:Request
&AdditinalRequest
res
:Response
next
: function(err?: any) => void
next
is the function to continue with the lifecycle including when using async
/await
or returning a Promise
.