From 76148b27f7501bac061992136852be4303370c8d Mon Sep 17 00:00:00 2001 From: Rigel Kent Date: Tue, 1 Jun 2021 01:36:53 +0200 Subject: refactor API errors to standard error format --- server/helpers/express-utils.ts | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) (limited to 'server/helpers/express-utils.ts') diff --git a/server/helpers/express-utils.ts b/server/helpers/express-utils.ts index 010c6961a..e3ff93cdd 100644 --- a/server/helpers/express-utils.ts +++ b/server/helpers/express-utils.ts @@ -8,6 +8,7 @@ import { isArray } from './custom-validators/misc' import { logger } from './logger' import { deleteFileAndCatch, generateRandomString } from './utils' import { getExtFromMimetype } from './video' +import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details' function buildNSFWFilter (res?: express.Response, paramNSFW?: string) { if (paramNSFW === 'true') return true @@ -125,6 +126,34 @@ function getCountVideos (req: express.Request) { return req.query.skipCount !== true } +// helpers added in server.ts and used in subsequent controllers used +const apiResponseHelpers = (req, res: express.Response, next = null) => { + res.fail = (options) => { + const { data, status, message, title, type, docs, instance } = { + data: null, + status: HttpStatusCode.BAD_REQUEST_400, + ...options + } + + const extension = new ProblemDocumentExtension({ + ...data, + docs: docs || res.docs + }) + + res.status(status) + res.setHeader('Content-Type', 'application/problem+json') + res.json(new ProblemDocument({ + status, + title, + instance, + type: type && '' + type, + detail: message + }, extension)) + } + + if (next !== null) next() +} + // --------------------------------------------------------------------------- export { @@ -134,5 +163,6 @@ export { badRequest, createReqFiles, cleanUpReqFiles, - getCountVideos + getCountVideos, + apiResponseHelpers } -- cgit v1.2.3