Application initialization events (#3680)

* Adds `not_found` hook

* Separate hooks and endpoints initialization process

* Adds additional application events

* Remove unused import

* Change the event order to accound for notFound and errorHandler

* Change emitAsync.catch to use the emitAsyncSafe function

* Updated docs, reordered table by lifecycle and usage
This commit is contained in:
WoLfulus
2021-02-08 14:30:09 -03:00
committed by GitHub
parent 42f0f01b13
commit b8e7c80b72
8 changed files with 141 additions and 81 deletions

View File

@@ -1,8 +1,29 @@
import { RequestHandler } from 'express';
import { RouteNotFoundException } from '../exceptions';
const notFound: RequestHandler = (req, res, next) => {
throw new RouteNotFoundException(req.path);
import emitter from '../emitter';
/**
* Handles not found routes.
*
* - If a hook throws an error, the error gets forwarded to the error handler.
* - If a hook returns true, the handler assumes the response has been
* processed and won't generate a response.
*
* @param req
* @param res
* @param next
*/
const notFound: RequestHandler = async (req, res, next) => {
try {
const ret = await emitter.emitAsync('request.not_found', req, res);
if (ret.reduce((prev, current) => current || prev, false)) {
return next();
}
next(new RouteNotFoundException(req.path));
} catch (err) {
next(err);
}
};
export default notFound;