@goatlab/fluent
Version:
Readable query Interface & API generator for TS and Node
97 lines (96 loc) • 3.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsonOrBooleanToJSON = exports.jsonToSchemaObject = void 0;
const tslib_1 = require("tslib");
const mapValues_1 = tslib_1.__importDefault(require("./mapValues"));
const openapi3_ts_1 = require("openapi3-ts");
function jsonToSchemaObject(json, visited = new Map()) {
const converted = 'x-loopback-converted';
const schema = visited.get(json);
if (schema != null && (0, openapi3_ts_1.isSchemaObject)(schema) && schema[converted] === false) {
return { $ref: `#/components/schemas/${json.title}` };
}
if (schema != null)
return schema;
const result = {
[converted]: false
};
visited.set(json, result);
const propsToIgnore = ['additionalItems', 'defaultProperties', 'typeof'];
for (const property in json) {
if (propsToIgnore.includes(property)) {
continue;
}
switch (property) {
case 'type': {
if (json.type === 'array' && !json.items) {
throw new Error('"items" property must be present if "type" is an array');
}
result.type = Array.isArray(json.type) ? json.type[0] : json.type;
break;
}
case 'allOf': {
result.allOf = json.allOf?.map(item => jsonToSchemaObject(item, visited));
break;
}
case 'anyOf': {
result.anyOf = json.anyOf?.map(item => jsonToSchemaObject(item, visited));
break;
}
case 'oneOf': {
result.oneOf = json.oneOf?.map(item => jsonToSchemaObject(item, visited));
break;
}
case 'definitions': {
result.definitions = (0, mapValues_1.default)(json.definitions, def => jsonToSchemaObject(jsonOrBooleanToJSON(def), visited));
break;
}
case 'properties': {
result.properties = (0, mapValues_1.default)(json.properties, item => jsonToSchemaObject(jsonOrBooleanToJSON(item), visited));
break;
}
case 'additionalProperties': {
if (typeof json.additionalProperties === 'boolean') {
result.additionalProperties = json.additionalProperties;
}
else {
result.additionalProperties = jsonToSchemaObject(json.additionalProperties, visited);
}
break;
}
case 'items': {
const items = Array.isArray(json.items) ? json.items[0] : json.items;
result.items = jsonToSchemaObject(jsonOrBooleanToJSON(items), visited);
break;
}
case '$ref': {
result.$ref = json.$ref.replace('#/definitions', '#/components/schemas');
break;
}
case 'examples': {
if (Array.isArray(json.examples)) {
result.example = json.examples[0];
}
break;
}
default: {
result[property] = json[property];
break;
}
}
}
delete result[converted];
const matched = result.description?.match(/^\(tsType: (.+), schemaOptions:/);
if (matched) {
result['x-typescript-type'] = matched[1];
}
return result;
}
exports.jsonToSchemaObject = jsonToSchemaObject;
function jsonOrBooleanToJSON(jsonOrBool) {
if (typeof jsonOrBool === 'object') {
return jsonOrBool;
}
return jsonOrBool ? {} : { not: {} };
}
exports.jsonOrBooleanToJSON = jsonOrBooleanToJSON;