-
Notifications
You must be signed in to change notification settings - Fork 1
/
validate.js
109 lines (100 loc) · 2.75 KB
/
validate.js
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const errorCodes = {
request_route_error: 'request_route_error',
request_schema_error: 'request_schema_error',
response_schema_error: 'response_schema_error'
}
module.exports = {
validateRequest,
validateResponse
}
function getErrorMessage (err) {
let message = `${err.message} in ${err.meta.in}.`
if (err.meta.rawErrors) {
message += ' ' + err.meta.rawErrors.map(e => e.error).join('; ')
}
return message
}
function customError ({ code, message, meta }) {
const err = Error(message)
err.code = code
err.meta = meta || {}
return err
}
function routePathMatchesDefinition (path, pattern) {
return path.replace(/:/g, '').replace(/\?$/, '') === pattern.replace(/{|}/g, '')
}
function validateRequestAttributes (chow, req) {
try {
return chow.validateRequest(req.path, {
method: req.method,
query: req.query,
body: req.body,
header: req.headers
})
} catch (err) {
const errorMessage = getErrorMessage(err)
throw customError({
meta: err.meta,
message: errorMessage,
code: errorCodes.request_schema_error
})
}
}
function validateResponseAttributes (chow, res, { method, path }) {
try {
return chow.validateResponse(path, {
status: '' + res.statusCode,
method: method,
body: res.body,
header: res.headers || {}
})
} catch (err) {
console.log(err)
const errorMessage = getErrorMessage(err)
throw customError({
meta: err.meta,
message: errorMessage,
code: errorCodes.response_schema_error
})
}
}
function validateRequest ({ req, operationAttributes, chow }) {
requireAttributes(operationAttributes)
if (operationAttributes.method.toLowerCase() !== req.method.toLowerCase()) {
throw customError({
meta: {
code: 500
},
message: "Route method doesn't match operationId from API definition",
code: errorCodes.request_route_error
})
}
if (!routePathMatchesDefinition(req.route.path, operationAttributes.path)) {
throw customError({
meta: {
code: 500
},
message: "Route path doesn't match operationId from API definition",
code: errorCodes.request_route_error
})
}
return validateRequestAttributes(chow, req)
}
function requireAttributes (operationAttributes) {
if (!operationAttributes) {
throw customError({
meta: {
code: 500
},
message: 'Specified operationId was not found in API definition',
code: errorCodes.request_route_error
})
}
}
function validateResponse ({ res, operationAttributes, chow, path }) {
requireAttributes(operationAttributes)
return validateResponseAttributes(chow, res, {
method: operationAttributes.method,
path: path || operationAttributes.path.replace(/{[^}]*}/g, '1')
})
}