api
Version:
Magical SDK generation from an OpenAPI definition 🪄
62 lines (61 loc) • 2.76 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
var json_schema_traverse_1 = __importDefault(require("json-schema-traverse"));
/**
* Run through a JSON Schema object and compose up an object containing default data for any schema
* property that is required and also has a defined default.
*
* Code partially adapted from the `json-schema-default` package but modified to only return
* defaults of required properties.
*
* @todo This is a good candidate to be moved into a core `oas` library method.
* @see {@link https://github.com/mdornseif/json-schema-default}
*/
function getJSONSchemaDefaults(jsonSchemas) {
return jsonSchemas
.map(function (_a) {
var _b;
var payloadType = _a.type, jsonSchema = _a.schema;
var defaults = {};
(0, json_schema_traverse_1["default"])(jsonSchema, function (schema, pointer, rootSchema, parentPointer, parentKeyword, parentSchema, indexProperty) {
if (!pointer.startsWith('/properties/')) {
return;
}
if (Array.isArray(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) && parentSchema.required.includes(indexProperty)) {
if (schema.type === 'object' && indexProperty) {
defaults[indexProperty] = {};
}
var destination_1 = defaults;
if (parentPointer) {
// To map nested objects correct we need to pick apart the parent pointer.
parentPointer
.replace(/\/properties/g, '')
.split('/')
.forEach(function (subSchema) {
if (subSchema === '') {
return;
}
destination_1 = (destination_1 === null || destination_1 === void 0 ? void 0 : destination_1[subSchema]) || {};
});
}
if (schema["default"] !== undefined) {
if (indexProperty !== undefined) {
destination_1[indexProperty] = schema["default"];
}
}
}
});
if (!Object.keys(defaults).length) {
return {};
}
return _b = {},
// @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
_b[payloadType] = defaults,
_b;
})
.reduce(function (prev, next) { return Object.assign(prev, next); });
}
exports["default"] = getJSONSchemaDefaults;