expectContenType utility middleware

improve error logging middleware
This commit is contained in:
Erik 2023-05-31 23:31:13 +03:00
parent e2a004f49f
commit eb49193f98
Signed by: Navy.gif
GPG Key ID: 2532FBBB61C65A68
4 changed files with 39 additions and 8 deletions

View File

@ -61,7 +61,7 @@
"broadcastLevel": 3
},
"databases": {
"messageBroker": {
"broker": {
"load": false
},
"mariadb": {

View File

@ -266,12 +266,18 @@ class Server extends EventEmitter {
req.remoteAddress = req.get('X-Forwarded-For') || req.socket.remoteAddress as string;
next();
}
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
#logError (err: Error, req: Request, res: Response, _next: NextFunction) {
this.#logger.error(`Unhandled error:\n${err.stack || err}`);
if (!req.complete)
res.status(500).send('An internal error was encountered');
#logError (err: Error, _req: Request, res: Response, _next: NextFunction) {
if (err.name === 'SyntaxError' && err.message.includes('JSON') && err.stack?.includes('body-parser')) {
if (!res.closed)
res.status(400).send(err.message);
// else quietly eat the error, user posted bad json
} else {
this.#logger.error(`Unhandled error:\n${err.stack || err}`);
if (!res.closed)
res.status(500).send('An internal error was encountered');
}
}
#logRequest (req: Request, res: Response, next: NextFunction) {

View File

@ -7,6 +7,8 @@ type FileFilterOptions = {
fileExtensions?: FileExtensions[]
}
type ContentTypeOptions = string | string[];
class UtilityMiddleware {
constructor () {
@ -21,6 +23,29 @@ class UtilityMiddleware {
};
}
static expectContentType (opts: ContentTypeOptions): MiddlewareFunction {
if (!opts)
throw new Error('Missing expected content type');
let options: string[] | null = null;
if ((opts instanceof Array))
options = opts;
else
options = [ opts ];
return (req: Request, res: Response, next: NextFunction): void => {
const contentType = req.get('content-type');
if (!contentType)
return void res.status(400).send('Must provide Content-Type');
if (!options?.includes(contentType))
return void res.status(400).send(`Invalid content type; Expecting ${options?.join('/')}`);
next();
};
}
static denyFileTypes (options: FileFilterOptions): MiddlewareFunction {
if (!options)
throw new Error('Need to supply options');

View File

@ -105,7 +105,7 @@ class PermissionManager {
PermissionManager.merge(to[key] as Permissions, from[key] as Permissions);
// eslint-disable-next-line no-undefined
} else if (!(key in to)) {
to[key] = from[key];
to[key] = from[key];
}
}
return to;