Init Decorators and Init Hooks
Init decorators are applied to module classes to pass metadata with extended data types. Init decorators can serve three roles:
- As a decorator for the root module (extending the data type passed to the
rootModuledecorator). For example,restRootModuleis an init decorator that can receive metadata with an extended data type. - As a decorator for a feature module (extending the data type passed to the
featureModuledecorator). For example,restModuleis an init decorator that can receive metadata with an extended data type. - As a decorator for extending either the root module or a feature module. In this case, it is recommended to name the decorator with the
init*prefix, for exampleinitRest,initTrpc,initGraphql, etc. In this role, multiple init decorators can be applied to a single module class.
Since init decorators accept module metadata with an extended type, they must be able to normalize and validate this metadata. This can be achieved through init hooks, which are passed into transformers during the creation of class decorators. Each transformer used for an init decorator must return an instance of a class that extends InitHooks:
import { InitHooks, InitDecorator, makeClassDecorator } from '@ditsmod/core';
// ...
// The methods of this class will normalize and validate the module metadata
class SomeInitHooks extends InitHooks<SomeInitRawMeta> {
// ...
}
// Init decorator transformer
function getInitHooks(data?: RawMetadata): InitHooks<RawMetadata> {
const metadata = Object.assign({}, data);
const initHooks = new SomeInitHooks(metadata);
initHooks.moduleRole = undefined;
// OR initHooks.moduleRole = 'root';
// OR initHooks.moduleRole = 'feature';
return initHooks;
}
// Creating the init decorator
const initSome: InitDecorator<RawMetadata, InitParams, InitMeta> = makeClassDecorator(getInitHooks);
A ready-made example of creating an init decorator can be found in the Ditsmod repository tests. In addition, you can check out a more complex but also more complete example of creating init decorators (restRootModule, restModule, and initRest), which are located in the @ditsmod/rest module.
If you can easily pass metadata to a module using a module with parameters, then creating an init decorator is not recommended. That is, whenever you want to create an init decorator, first consider using a module with parameters.