-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathprocess-schema.js
More file actions
61 lines (52 loc) · 2.02 KB
/
process-schema.js
File metadata and controls
61 lines (52 loc) · 2.02 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
/**
* @typedef {Record<string, any> | boolean} JSONSchema
* A JSON Schema node — can be an object schema or a boolean schema.
*/
/**
* @typedef {Object} SchemaVisitor
* @property {(schema: JSONSchema, context?: Record<string, unknown>) => JSONSchema | void} [schema]
* @property {(obj: JSONSchema, context?: Record<string, unknown>) => JSONSchema | void} [object]
* @property {(arr: JSONSchema[], context?: Record<string, unknown>) => void} [array]
*/
/**
* Recursively processes a JSON Schema using the visitor pattern.
* @param {SchemaVisitor} visitor - Visitor functions to apply.
* @param {JSONSchema} json - JSON Schema to process.
* @param {Record<string, unknown>} [context] - Optional shared context.
* @returns {JSONSchema} - The processed JSON Schema.
*/
const NESTED_WITH_NAME = ["definitions", "properties"];
const NESTED_DIRECT = ["items", "additionalProperties", "not"];
const NESTED_ARRAY = ["oneOf", "anyOf", "allOf"];
const processSchema = (visitor, json, context) => {
if (!json || typeof json !== "object") return json; // safety check
json = { ...json };
if (typeof visitor?.schema === "function") {
json = visitor.schema(json, context) || json;
}
for (const name of NESTED_WITH_NAME) {
if (json[name] && typeof json[name] === "object" && !Array.isArray(json[name])) {
if (typeof visitor?.object === "function") {
json[name] = visitor.object(json[name], context) || json[name];
}
for (const key of Object.keys(json[name])) {
json[name][key] = processSchema(visitor, json[name][key], context);
}
}
}
for (const name of NESTED_DIRECT) {
if (json[name] && typeof json[name] === "object" && !Array.isArray(json[name])) {
json[name] = processSchema(visitor, json[name], context);
}
}
for (const name of NESTED_ARRAY) {
if (Array.isArray(json[name])) {
json[name] = json[name].map((item) => processSchema(visitor, item, context));
if (typeof visitor?.array === "function") {
visitor.array(json[name], context);
}
}
}
return json;
};
module.exports = processSchema;