before/after
Methods for performing actions before and after the execution of the main method are provided for add/modify/remove operations. To use this mechanism, you need to define the corresponding method in the class with classic input and output parameters (IAPIRequest and IAPIResponse).
before
For each method, the presence of a corresponding method in the class is checked. For add — beforeAdd, for modify — beforeModify, for remove — beforeRemove.
The parameters passed to the main method are passed to the called methods.
after
Similarly, for each method, the presence of a corresponding method in the class is checked. For add — afterAdd, for modify — afterModify, for remove — afterRemove.
An object with id (for add it will be the id of the created record), origParams (parameters passed to the main method), and a system rollback_key is passed to the called methods.
Common methods
You can also define a common method, simply “before”/“after” — it will be triggered (if present) before/after any of the actions (add/modify/remove).
Examples
/**
* Hook before add: if alias is not passed, transliterate name to alias.
*/
async beforeAdd(r: IAPIRequest): Promise<IAPIResponse> {
const params = r.data.params
if (params.alias) return new UserOk('ok')
if (!params.name) return new MyError('name not passed', {params})
params.alias = slugify(params.name)
return new UserOk('ok')
}
or
/**
* If the state of activity has changed, then update the current version
*/
async afterModify(r: IAPIRequest): Promise<IAPIResponse> {
const params = r.data.params
const origParams = params.origParams
const id = params.id
if (!id) return new MyError('id not passed', {params})
if (!origParams.hasOwnProperty('is_active')) return new UserOk('ok')
return r.api(Document, 'setActualPriorityByDocId', {id})
}