forked from theodo/serverless-openapi
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.ts
58 lines (45 loc) · 1.25 KB
/
parse.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
import { JSONSchema7 } from "json-schema";
import * as $RefParser from "json-schema-ref-parser";
import * as _ from "lodash";
import * as path from "path";
import { Model } from "./types";
import { cleanSchema } from "./utils";
function updateReferences(schema: JSONSchema7): JSONSchema7 {
if (!schema) {
return schema;
}
const cloned = _.cloneDeep(schema);
if (cloned.$ref) {
return {
...cloned,
$ref: cloned.$ref.replace("#/definitions", "#/components/schemas"),
};
}
for (const key of Object.getOwnPropertyNames(cloned)) {
const value = cloned[key];
if (typeof value === "object") {
cloned[key] = updateReferences(value);
}
}
return cloned;
}
export async function parseModels(models: Array<Model>, root: string): Promise<{}> {
const schemas = {};
if (!_.isArrayLike(models)) {
models = [];
}
for (const model of models) {
if (!model.schema) {
continue;
}
const schema = (
typeof model.schema === "string"
? await $RefParser.bundle(path.resolve(root, model.schema))
: model.schema
) as JSONSchema7;
_.assign(schemas, updateReferences(schema.definitions), {
[model.name]: updateReferences(cleanSchema(schema)),
});
}
return schemas;
}