-
-
Notifications
You must be signed in to change notification settings - Fork 211
/
util.ts
87 lines (83 loc) · 2.07 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import ono from 'ono';
import * as Ajv from 'ajv';
import { Request } from 'express';
import { ValidationError } from '../framework/types';
export function extractContentType(req: Request): string | null {
let contentType = req.headers['content-type'];
if (!contentType) {
return null;
}
let end = contentType.indexOf(';');
end = end === -1 ? contentType.length : end;
if (contentType) {
return contentType.substring(0, end);
}
return contentType;
}
const _validationError = (
status: number,
path: string,
message: string,
errors?: any, // TODO rename - normalize...something else
): ValidationError => ({
status,
errors: [
{
path,
message,
...({ errors } || {}),
},
],
});
export function validationError(
status: number,
path: string,
message: string,
): ValidationError {
const err = _validationError(status, path, message);
return ono(err, message);
}
/**
* (side-effecting) modifies the errors object
* TODO - do this some other way
* @param errors
*/
export function augmentAjvErrors(
errors: Ajv.ErrorObject[] = [],
): Ajv.ErrorObject[] {
errors.forEach(e => {
if (e.keyword === 'enum') {
const params: any = e.params;
const allowedEnumValues = params && params.allowedValues;
e.message = !!allowedEnumValues
? `${e.message}: ${allowedEnumValues.join(', ')}`
: e.message;
}
});
return errors;
}
export function ajvErrorsToValidatorError(
status: number,
errors: Ajv.ErrorObject[],
): ValidationError {
return {
status,
errors: errors.map(e => {
const params: any = e.params;
const required =
params &&
params.missingProperty &&
e.dataPath + '.' + params.missingProperty;
const additionalProperty =
params &&
params.additionalProperty &&
e.dataPath + '.' + params.additionalProperty;
const path = required || additionalProperty || e.dataPath || e.schemaPath;
return {
path,
message: e.message,
errorCode: `${e.keyword}.openapi.validation`,
};
}),
};
}