@rapharacing/schemas
Version:
OpenAPI to JSON Schema to be used with middy for CC response validation
69 lines (54 loc) • 1.71 kB
JavaScript
/* eslint-disable no-restricted-syntax */
/* eslint-disable guard-for-in */
/* eslint-disable no-console */
import {
quicktype,
InputData,
JSONSchemaInput,
JSONSchemaStore
} from "quicktype-core";
import fs from "fs-extra";
const SCHEMAS_PATH = "./src/schemas";
const INTERFACES_PATH = "./src/interfaces";
async function quicktypeJSONSchema(targetLanguage, typeName, jsonSchemaString) {
const schemaInput = new JSONSchemaInput(new JSONSchemaStore());
await schemaInput.addSource({ name: typeName, schema: jsonSchemaString });
const inputData = new InputData();
inputData.addInput(schemaInput);
return quicktype({
inputData,
lang: targetLanguage,
allPropertiesOptional: true,
rendererOptions: {
"just-types": true,
"runtime-typecheck": false
}
});
}
const generateInterfaces = files => {
const disallowed = "_definitions.json";
const filterdFiles = files.filter(f => f !== disallowed);
for (const idx in filterdFiles) {
const file = filterdFiles[idx];
const string = fs.readFile(file);
const json = fs.readJsonSync(`${SCHEMAS_PATH}/${file}`);
const { title } = json;
quicktypeJSONSchema("typescript", title, string);
}
};
try {
console.log(`Generating definitions from ${SCHEMAS_PATH}`);
// Ensures that a directory is empty.
// Deletes directory contents if the directory is not empty.
// If the directory does not exist, it is created. The directory itself is not deleted.
fs.emptyDir(INTERFACES_PATH, error => {
if (error) throw new Error(error);
});
// Get a list of schemas
fs.readdir(SCHEMAS_PATH, (error, files) => {
if (error) throw new Error(error);
if (files) generateInterfaces(files);
});
} catch (error) {
throw new Error(error);
}