@spec2ts/jsonschema
Version:
Utility to convert JSON Schemas to Typescript using TypeScript native compiler
40 lines (39 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseSchema = exports.parseSchemaFile = void 0;
const path = require("path");
const json_schema_ref_parser_1 = require("@apidevtools/json-schema-ref-parser");
const core = require("@spec2ts/core");
const core_parser_1 = require("./core-parser");
async function parseSchemaFile(file, options = {}) {
const schema = await json_schema_ref_parser_1.default.parse(file);
return parseSchema(schema, {
name: (0, core_parser_1.getSchemaName)(schema, file),
cwd: path.resolve(path.dirname(file)) + "/",
...options
});
}
exports.parseSchemaFile = parseSchemaFile;
async function parseSchema(schema, options = {}) {
const context = await (0, core_parser_1.createContext)(schema, options);
const type = (0, core_parser_1.getTypeFromSchema)(context.schema, context);
(0, core_parser_1.parseDefinitions)(context.schema, context);
const res = [
...context.imports,
...context.aliases
];
// Ignore schema type if schema is only composed of definitions
if ((type === core.keywordType.any || type === core.keywordType.unknown) && !context.schema.type && context.schema.definitions) {
return res;
}
let decla = core.createTypeOrInterfaceDeclaration({
modifiers: [core.modifier.export],
name: options.name || (0, core_parser_1.getSchemaName)(context.schema),
type
});
if (schema.description) {
decla = core.addComment(decla, schema.description);
}
return [...res, decla];
}
exports.parseSchema = parseSchema;