From 73635a1bddf1c676556df8743732a7026d7844fc Mon Sep 17 00:00:00 2001 From: Andrey Chalkin Date: Fri, 20 Oct 2023 00:33:49 +0200 Subject: [PATCH] docs: updated Plugins Development.md --- docs/Plugins Development.md | 48 +++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/docs/Plugins Development.md b/docs/Plugins Development.md index 33d9a10e..16564e79 100644 --- a/docs/Plugins Development.md +++ b/docs/Plugins Development.md @@ -19,6 +19,54 @@ Fastify decorators provides several hooks: - `appReady` - executes when Fastify decorators done initialization - `appDestroy` - executes before Fastify instance destroyed +### Class loader + +"Class loader" is a function used to instantiate Controller/RequestHandler/Service/etc. +It accepts class itself and scope. + +where: + +- class itself could be Controller/RequestHandler or any other class type defined in the plugin (f.e. Service) +- scope is where this class were requested - FastifyInstance or FastifyRequest. + +Registration of class loader SHOULD be done on `appInit` stage by decorating FastifyInstance. + +*example*: + +```typescript +import { CLASS_LOADER, createInitializationHook } from 'fastify-decorators/plugins'; + +createInitializationHook('appInit', (fastify) => { + fastify.decorate(CLASS_LOADER, (clazz: new () => any, _scope) => new clazz) +}) +``` + +### Handlers, Hooks and Error Handlers + +In addition to normal Lifecycle hooks, +Fastify Decorators provides interfaces and symbols to interact with registered handlers and hooks. + +This functionality can be used to implicitly decorate methods + +*Example: log arguments when any hook is called*: + +```typescript +import { FastifyInstance } from 'fastify'; +import { createInitializationHook, Registrable, hasHooks, HOOKS, IHook } from 'fastify-decorators/plugins'; + +createInitializationHook('beforeControllerCreation', (fastifyInstance: FastifyInstance, target: Registrable) => { + if (hasHooks(target)) { + for (const hook of target[HOOKS]) { // hook has type IHook + const _method = target[hook.handlerName]; + target[hook.handlerName] = function logged(...args: any) { + console.log('Hook called with args: ', args) + return _method.apply(this, args) + } + } + } +}) +``` + ### Fastify Lifecycle: Please refer to [Fastify docs]