UNPKG

2.87 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2018,2020. All Rights Reserved.
2// Node module: @loopback/rest
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6import HttpErrors from 'http-errors';
7
8export namespace RestHttpErrors {
9 export function invalidData<T, Props extends object = {}>(
10 data: T,
11 name: string,
12 extraProperties?: Props,
13 ): HttpErrors.HttpError & Props {
14 const msg = `Invalid data ${JSON.stringify(data)} for parameter "${name}".`;
15 return Object.assign(
16 new HttpErrors.BadRequest(msg),
17 {
18 code: 'INVALID_PARAMETER_VALUE',
19 parameterName: name,
20 },
21 extraProperties,
22 );
23 }
24
25 export function unsupportedMediaType(
26 contentType: string,
27 allowedTypes: string[] = [],
28 ) {
29 const msg = allowedTypes?.length
30 ? `Content-type ${contentType} does not match [${allowedTypes}].`
31 : `Content-type ${contentType} is not supported.`;
32 return Object.assign(new HttpErrors.UnsupportedMediaType(msg), {
33 code: 'UNSUPPORTED_MEDIA_TYPE',
34 contentType: contentType,
35 allowedMediaTypes: allowedTypes,
36 });
37 }
38
39 export function missingRequired(name: string): HttpErrors.HttpError {
40 const msg = `Required parameter ${name} is missing!`;
41 return Object.assign(new HttpErrors.BadRequest(msg), {
42 code: 'MISSING_REQUIRED_PARAMETER',
43 parameterName: name,
44 });
45 }
46
47 export function invalidParamLocation(location: string): HttpErrors.HttpError {
48 const msg = `Parameters with "in: ${location}" are not supported yet.`;
49 return new HttpErrors.NotImplemented(msg);
50 }
51
52 export const INVALID_REQUEST_BODY_MESSAGE =
53 'The request body is invalid. See error object `details` property for more info.';
54
55 export function invalidRequestBody(
56 details: ValidationErrorDetails[],
57 ): HttpErrors.HttpError & {details: ValidationErrorDetails[]} {
58 return Object.assign(
59 new HttpErrors.UnprocessableEntity(INVALID_REQUEST_BODY_MESSAGE),
60 {
61 code: 'VALIDATION_FAILED',
62 details,
63 },
64 );
65 }
66
67 /**
68 * An invalid request body error contains a `details` property as the machine-readable error.
69 * Each entry in `error.details` contains 4 attributes: `path`, `code`, `info` and `message`.
70 * `ValidationErrorDetails` defines the type of each entry, which is an object.
71 * The type of `error.details` is `ValidationErrorDetails[]`.
72 */
73 export interface ValidationErrorDetails {
74 /**
75 * A path to the invalid field.
76 */
77 path: string;
78 /**
79 * A single word code represents the error's type.
80 */
81 code: string;
82 /**
83 * A human readable description of the error.
84 */
85 message: string;
86 /**
87 * Some additional details that the 3 attributes above don't cover.
88 */
89 info: object;
90 }
91}