-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathschemaHandler.js
More file actions
305 lines (260 loc) · 8.4 KB
/
schemaHandler.js
File metadata and controls
305 lines (260 loc) · 8.4 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"use strict";
const isEqual = require("node:util").isDeepStrictEqual;
const path = require("path");
const $RefParser = require("@apidevtools/json-schema-ref-parser");
const SchemaConvertor = require("json-schema-for-openapi");
const { v4: uuid } = require("uuid");
class SchemaHandler {
constructor(serverless, openAPI, logger) {
this.logger = logger;
this.apiGatewayModels =
serverless.service?.provider?.apiGateway?.request?.schemas || {};
this.documentation = serverless.service.custom.documentation;
this.openAPI = openAPI;
this.modelReferences = {};
this.__standardiseModels();
try {
this.logger.verbose(
`Trying to resolve Ref-Parser config from: ${path.resolve(
"options",
"ref-parser.js"
)}`
);
this.refParserOptions = require(path.resolve("options", "ref-parser.js"));
} catch (err) {
this.refParserOptions = {};
}
}
/**
* Standardises the models to a specific format
*/
__standardiseModels() {
const standardModel = (model) => {
if (model.schema) {
return model;
}
if (Object.keys(model.content).length === 1) {
const contentType = Object.keys(model.content)[0];
model.contentType = contentType;
model.contentTypes = [contentType];
model.schema = model.content[contentType].schema;
} else {
model.contentType = null;
model.contentTypes = Object.keys(model.content);
model.schema = null;
model.schemas = {};
for (const key in model.content) {
Object.assign(model.schemas, {[key]: {schema: model.content[key].schema}});
}
// model.schema = model.content[contentType].schema;
}
return model;
};
const standardisedModels =
this.documentation?.models?.map(standardModel) || [];
const standardisedModelsList =
this.documentation?.modelsList?.map(standardModel) || [];
const standardisedGatewayModels =
Object.keys(this.apiGatewayModels).flatMap((key) => {
const gatewayModel = this.apiGatewayModels[key];
return standardModel(gatewayModel);
}) || [];
this.models = standardisedModels.concat(
standardisedModelsList,
standardisedGatewayModels
);
}
async addModelsToOpenAPI() {
for (const model of this.models) {
const modelName = model.name;
const schemas = []
if (model.schema){
// const modelSchema = model.schema;
schemas.push(model.schema)
} else {
for (const key in model.schemas) {
schemas.push(model.schemas[key].schema);
}
}
for (const modelSchema of schemas) {
const convertedSchemas = await this.__dereferenceAndConvert(
modelSchema,
modelName,
model
).catch((err) => {
if (err instanceof Error) throw err;
else return err;
});
if (
typeof convertedSchemas.schemas === "object" &&
!Array.isArray(convertedSchemas.schemas) &&
convertedSchemas.schemas !== null
) {
for (const [schemaName, schemaValue] of Object.entries(
convertedSchemas.schemas
)) {
if (schemaName === modelName) {
this.modelReferences[
schemaName
] = `#/components/schemas/${modelName}`;
}
this.__addToComponents("schemas", schemaValue, schemaName);
}
} else {
throw new Error(
`There was an error converting the ${
model.name
} schema. Model received looks like: \n\n${JSON.stringify(
model
)}. The convereted schema looks like \n\n${JSON.stringify(
convertedSchemas
)}`
);
}
}
}
}
async createSchema(name, schema) {
let originalName = name;
let finalName = name;
if (this.modelReferences[name] && schema === undefined) {
return this.modelReferences[name];
}
const convertedSchemas = await this.__dereferenceAndConvert(schema, name, {
name,
schema,
}).catch((err) => {
throw err;
});
for (const [schemaName, schemaValue] of Object.entries(
convertedSchemas.schemas
)) {
if (this.__existsInComponents(schemaName)) {
if (this.__isTheSameSchema(schemaValue, schemaName) === false) {
if (schemaName === originalName) {
finalName = `${schemaName}-${uuid()}`;
this.__addToComponents("schemas", schemaValue, finalName);
} else {
this.__addToComponents("schemas", schemaValue, schemaName);
}
}
} else {
this.__addToComponents("schemas", schemaValue, schemaName);
}
}
return `#/components/schemas/${finalName}`;
}
async __dereferenceAndConvert(schema, name, model) {
this.logger.verbose(`dereferencing model: ${name}`);
const dereferencedSchema = await this.__dereferenceSchema(schema).catch(
(err) => {
this.__checkForHTTPErrorsAndThrow(err, model);
this.__checkForMissingPathAndThrow(err);
return schema;
}
);
this.logger.verbose(
`dereferenced model: ${JSON.stringify(dereferencedSchema)}`
);
this.logger.verbose(`converting model: ${name}`);
const convertedSchemas = SchemaConvertor.convert(dereferencedSchema, name);
this.logger.verbose(
`converted schemas: ${JSON.stringify(convertedSchemas)}`
);
return convertedSchemas;
}
async __dereferenceSchema(schema) {
const bundledSchema = await $RefParser
.bundle(schema, this.refParserOptions)
.catch((err) => {
throw err;
});
let deReferencedSchema = await $RefParser
.dereference(bundledSchema, this.refParserOptions)
.catch((err) => {
throw err;
});
// deal with schemas that have been de-referenced poorly: naive
if (deReferencedSchema?.$ref === "#") {
const oldRef = bundledSchema.$ref;
const path = oldRef.split("/");
const pathTitle = path[path.length - 1];
const referencedProperties = deReferencedSchema.definitions[pathTitle];
Object.assign(deReferencedSchema, { ...referencedProperties });
delete deReferencedSchema.$ref;
deReferencedSchema = await this.__dereferenceSchema(
deReferencedSchema
).catch((err) => {
throw err;
});
}
return deReferencedSchema;
}
/**
* @function existsInComponents
* @param {string} name - The name of the Schema
* @returns {boolean} Whether it exists in components already
*/
__existsInComponents(name) {
return Boolean(this.openAPI?.components?.schemas?.[name]);
}
/**
* @function isTheSameSchema
* @param {object} schema - The schema value
* @param {string} otherSchemaName - The name of the schema
* @returns {boolean} Whether the schema provided is the same one as in components already
*/
__isTheSameSchema(schema, otherSchemaName) {
return isEqual(schema, this.openAPI.components.schemas[otherSchemaName]);
}
/**
* @function addToComponents
* @param {string} type - The component type
* @param {object} schema - The schema
* @param {string} name - The name of the schema
*/
__addToComponents(type, schema, name) {
const schemaObj = {
[name]: schema,
};
if (this.openAPI?.components) {
if (this.openAPI.components[type]) {
Object.assign(this.openAPI.components[type], schemaObj);
} else {
Object.assign(this.openAPI.components, { [type]: schemaObj });
}
} else {
const components = {
components: {
[type]: schemaObj,
},
};
Object.assign(this.openAPI, components);
}
}
__checkForMissingPathAndThrow(error) {
if (error.message === "Expected a file path, URL, or object. Got undefined")
throw error;
}
__checkForHTTPErrorsAndThrow(error, model) {
if (error.errors) {
for (const err of error?.errors) {
this.__HTTPError(err, model);
}
} else {
this.__HTTPError(error, model);
}
}
__HTTPError(error, model) {
if (error.message.includes("HTTP ERROR")) {
throw new Error(
`There was an error dereferencing ${
model.name
} schema. \n\n dereferencing message: ${
error.message
} \n\n Model received: ${JSON.stringify(model)}`
);
}
}
}
module.exports = SchemaHandler;