]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
e030bfb5 | 2 | import { ProblemDocument, ProblemDocumentExtension } from 'http-problem-details' |
38d69d65 | 3 | import { logger } from '@server/helpers/logger' |
c0e8b12e | 4 | import { HttpStatusCode } from '@shared/models' |
e030bfb5 C |
5 | |
6 | function apiFailMiddleware (req: express.Request, res: express.Response, next: express.NextFunction) { | |
7 | res.fail = options => { | |
8 | const { status = HttpStatusCode.BAD_REQUEST_400, message, title, type, data, instance } = options | |
9 | ||
10 | const extension = new ProblemDocumentExtension({ | |
11 | ...data, | |
12 | ||
13 | docs: res.locals.docUrl, | |
14 | code: type, | |
15 | ||
16 | // For <= 3.2 compatibility | |
17 | error: message | |
18 | }) | |
19 | ||
20 | res.status(status) | |
21 | res.setHeader('Content-Type', 'application/problem+json') | |
38d69d65 C |
22 | |
23 | const json = new ProblemDocument({ | |
e030bfb5 C |
24 | status, |
25 | title, | |
26 | instance, | |
27 | ||
28 | detail: message, | |
29 | ||
30 | type: type | |
31 | ? `https://docs.joinpeertube.org/api-rest-reference.html#section/Errors/${type}` | |
32 | : undefined | |
38d69d65 C |
33 | }, extension) |
34 | ||
35 | logger.debug('Bad HTTP request.', { json }) | |
36 | ||
37 | res.json(json) | |
e030bfb5 C |
38 | } |
39 | ||
40 | if (next) next() | |
41 | } | |
42 | ||
43 | export { | |
44 | apiFailMiddleware | |
45 | } |