Skip to content

Instantly share code, notes, and snippets.

@michaelmang
Created January 6, 2022 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaelmang/c86aeb5e96c5408371efcac7c4523d82 to your computer and use it in GitHub Desktop.
Save michaelmang/c86aeb5e96c5408371efcac7c4523d82 to your computer and use it in GitHub Desktop.
Contract Dictionary (Like Style Dictionary for Schemas)
import glob from 'glob';
import fs from 'fs';
import { compile as compileTypeScript } from 'json-schema-to-typescript';
import path from 'path';
import rimraf from 'rimraf';
const FORMATS = Object.freeze({
json: 'json',
typescript: 'typescript',
});
const EXTENSIONS = Object.freeze({
json: '.jsonc',
typescript: '.ts',
});
const config = {
buildPath: 'build',
formats: Object.values(FORMATS),
};
function clean() {
rimraf.sync(config.buildPath);
fs.mkdirSync(config.buildPath);
}
function parse(file) {
return {
data: JSON.parse(fs.readFileSync(file, 'utf8')),
name: path.parse(file).name,
};
}
async function compile({ data, type }) {
if (type === FORMATS.json) {
return data;
}
if (type === FORMATS.typescript) {
return await compileTypeScript(data);
}
}
async function format({ data, name, type }) {
const result = await compile({ data, type });
write({ data: result, name, type });
}
function prettify({ data, type }) {
if (type === FORMATS.typescript) {
return data;
}
if (type === FORMATS.json) {
// TODO: Use prettier (or similar)
return JSON.stringify(data, null, 2);
}
}
function write({ data, name, type }) {
fs.writeFileSync(`${config.buildPath}/${name}${EXTENSIONS[type]}`, prettify({ data, type }));
}
const options = null;
glob('schemas/**/*.jsonc', options, (error, files) => {
if (error) {
throw error;
}
clean();
files.forEach((file) => {
const { data, name } = parse(file);
config.formats.forEach((type) => {
format({ data, name, type });
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment