This repository has been archived by the owner on May 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
209 lines (177 loc) · 5.58 KB
/
index.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
var convert = require('openapi-jsonschema-parameters');
var jsonschema = require('jsonschema');
var SchemaError = jsonschema.SchemaError;
var JsonschemaValidator = jsonschema.Validator;
var loggingKey = require('./package.json').name + ': ';
var LOCAL_DEFINITION_REGEX = /^#\/([^\/]+)\/([^\/]+)$/;
module.exports = validate;
function validate(args) {
if (!args) {
throw new Error(loggingKey + 'missing args argument');
}
if (!Array.isArray(args.parameters)) {
throw new Error(loggingKey + 'args.parameters must be an Array');
}
var schemas = convert(args.parameters);
var errorTransformer = typeof args.errorTransformer === 'function' &&
args.errorTransformer;
var errorMapper = errorTransformer ?
extendedErrorMapper(errorTransformer) :
toOpenapiValidationError;
var bodySchema = schemas.body;
var bodyValidationSchema;
var headersSchema = lowercasedHeaders(schemas.headers);
var formDataSchema = schemas.formData;
var pathSchema = schemas.path;
var querySchema = schemas.query;
var v = new JsonschemaValidator();
var isBodyRequired = args.parameters.filter(byBodyParameters).length > 0;
if (args.customFormats) {
Object.keys(args.customFormats).forEach(function(format) {
var func = args.customFormats[format];
if (typeof func === 'function') {
v.customFormats[format] = func;
}
});
}
if (bodySchema) {
bodyValidationSchema = {
properties: {
body: bodySchema
}
};
}
if (args.schemas) {
if (Array.isArray(args.schemas)) {
args.schemas.forEach(function(schema) {
var id = schema.id;
if (id) {
var localSchemaPath = LOCAL_DEFINITION_REGEX.exec(id);
if (localSchemaPath && bodyValidationSchema) {
var definitions = bodyValidationSchema[localSchemaPath[1]];
if (!definitions) {
definitions = bodyValidationSchema[localSchemaPath[1]] = {};
}
definitions[localSchemaPath[2]] = schema;
}
v.addSchema(schema, id);
} else {
console.warn(loggingKey, 'igorning schema without id property');
}
});
} else if (bodySchema) {
bodyValidationSchema.definitions = args.schemas;
}
}
if (args.externalSchemas) {
Object.keys(args.externalSchemas).forEach(function(id) {
v.addSchema(args.externalSchemas[id], id);
});
}
return function(req, res, next) {
var errors = [];
var err;
var schemaError;
if (bodySchema) {
if (req.body) {
try {
var validation = v.validate({body: req.body}, bodyValidationSchema);
errors.push.apply(errors, withAddedLocation('body', validation.errors));
} catch(e) {
e.location = 'body';
schemaError = e;
}
} else {
schemaError = {
location: 'body',
message: 'req.body was not present in the request. Is a body-parser being used?',
schema: bodySchema
};
}
}
if (req.body && formDataSchema) {
errors.push.apply(errors, withAddedLocation('formData', v.validate(
req.body, formDataSchema).errors));
}
if (req.params && pathSchema) {
errors.push.apply(errors, withAddedLocation('path', v.validate(
req.params, pathSchema).errors));
}
if (req.headers && headersSchema) {
errors.push.apply(errors, withAddedLocation('headers', v.validate(
req.headers, headersSchema).errors));
}
if (req.query && querySchema) {
errors.push.apply(errors, withAddedLocation('query', v.validate(
req.query, querySchema).errors));
}
if (errors.length) {
err = {
status: 400,
errors: errors.map(errorMapper)
};
} else if (schemaError) {
err = {
status: 400,
errors: [schemaError]
};
}
next(err);
};
}
function byBodyParameters(param) {
return param.in === 'body' || param.in === 'formData';
}
function extendedErrorMapper(mapper) {
return function(jsonSchemaError) {
return mapper(toOpenapiValidationError(jsonSchemaError), jsonSchemaError);
};
}
function lowercasedHeaders(headersSchema) {
if (headersSchema) {
var properties = headersSchema.properties;
Object.keys(properties).forEach(function(header) {
var property = properties[header];
delete properties[header];
properties[header.toLowerCase()] = property;
});
if (headersSchema.required && headersSchema.required.length) {
headersSchema.required = headersSchema.required.map(function(header) {
return header.toLowerCase();
});
}
}
return headersSchema;
}
function toOpenapiValidationError(error) {
return stripBodyInfo({
path: error.property.replace(
error.location === 'body' ?
/^instance\.body\.?/ :
/^instance\.?/, '') || error.argument,
errorCode: error.name + '.openapi.validation',
message: error.stack,
location: error.location
});
}
function stripBodyInfo(error) {
if (error.location === 'body') {
if (typeof error.path === 'string') {
error.path = error.path.replace(/^body\./, '');
} else {
// Removing to avoid breaking clients that are expecting strings.
delete error.path;
}
error.message = error.message.replace(/^instance\.body\./, 'instance.');
error.message = error.message.replace(/^instance\.body /, 'instance ');
}
return error;
}
function withAddedLocation(location, errors) {
if (errors) {
errors.forEach(function(error) {
error.location = location;
});
}
return errors;
}