forked from conqa/serverless-openapi-documentation
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathparse.ts
62 lines (49 loc) · 1.41 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
59
60
61
62
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) {
let referencedValue = cloned.$ref
.replace("#/definitions", "#/components/schemas") // json schema syntax
.replace(/{{model: (\w+)}}/, "#/components/schemas/$1"); // swagger 2.0 syntax
return {
...cloned,
$ref: referencedValue
};
}
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)) {
throw new Error("Empty 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;
}