expectContenType utility middleware
improve error logging middleware
This commit is contained in:
parent
e2a004f49f
commit
eb49193f98
@ -61,7 +61,7 @@
|
||||
"broadcastLevel": 3
|
||||
},
|
||||
"databases": {
|
||||
"messageBroker": {
|
||||
"broker": {
|
||||
"load": false
|
||||
},
|
||||
"mariadb": {
|
||||
|
@ -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) {
|
||||
|
@ -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');
|
||||
|
@ -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;
|
||||
|
Loading…
Reference in New Issue
Block a user