Skip to content

Commit

Permalink
Add new file for generating JSON schema from TypeScript file
Browse files Browse the repository at this point in the history
- Added a new TypeScript file `generate.ts` to handle the generation of JSON schema from a given TypeScript file. The script validates input parameters, generates a UUID, creates the schema configuration, and writes the resulting JSON schema to an output file.
  • Loading branch information
Mearman committed Mar 14, 2024
1 parent dc16d55 commit ded83f7
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/util/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import fs from "fs";
import path, { dirname } from "path";
import { Config, createGenerator } from "ts-json-schema-generator";
import { fileURLToPath } from "url";

const file = process.argv[2];
if (!file) {
console.error("No file path provided");
process.exit(1);
} else if (!fs.existsSync(file)) {
console.error("Provided path does not exist");
process.exit(1);
} else if (!fs.lstatSync(file).isFile()) {
console.error("Provided path is not a file");
process.exit(1);
} else if (!file.endsWith(".ts")) {
console.error("Provided file is not a typescript file");
process.exit(1);
}
const rootType = process.argv[3].trim();
if (!rootType) {
console.error("No root type provided");
process.exit(1);
} else if (rootType.length === 0) {
console.error("Root type cannot be empty");
process.exit(1);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const projectRoot = path.resolve(__dirname, "../../");
const srcRoot = path.join(projectRoot, "src");
const tsconfig = path.join(projectRoot, "tsconfig.json");

function generate(file: string, rootType: string = "JsonCanvas") {
const relativePath = path.relative(__dirname, file);
const config: Config = {
path: relativePath,
tsconfig: tsconfig,
type: rootType,
topRef: true,
additionalProperties: false,
sortProps: true,
};

const outputPath = path.join(projectRoot, "jsoncanvas.schema.json");
const gnerator = createGenerator(config);
const schema = gnerator.createSchema(config.type);
const schemaString = JSON.stringify(schema, null, 2);
fs.writeFileSync(outputPath, schemaString);
}

generate(file);

0 comments on commit ded83f7

Please sign in to comment.