Skip to content

Commit

Permalink
Replace json-schema-to-typescript by quicktype
Browse files Browse the repository at this point in the history
  • Loading branch information
fredericbarthelet committed Dec 24, 2020
1 parent 3d43d14 commit 5fced12
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 40 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
"eslint-config-prettier": "^7.1.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-prettier": "^3.3.0",
"json-schema-to-typescript": "^10.0.2",
"prettier": "^2.2.1",
"quicktype-core": "^6.0.69",
"serverless": "*",
"typescript": "^4.0.5"
}
Expand Down
57 changes: 18 additions & 39 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { compile } from "json-schema-to-typescript";
import fs from "fs";
import { InputData, JSONSchemaInput, quicktype } from "quicktype-core";
import { writeFileSync } from "fs";
import type { JSONSchema4 } from "json-schema";

interface Serverless {
Expand Down Expand Up @@ -27,45 +27,24 @@ class ConfigSchemaHandlerTypescriptDefinitionsPlugin {
};

async generateSchema() {
/**
* https://github.com/serverless/typescript/issues/4
* JSON Schema v6 `const` keyword converted to `enum`
*/
const normalizedSchema = replaceAllConstForEnum(this.schema);

/**
* ignoreMinAndMaxItems: true -> maxItems: 100 in provider.s3.corsConfiguration definition is generating 100 tuples
*/
const compiledDefinitions = await compile(normalizedSchema, "AWS", {
ignoreMinAndMaxItems: true,
unreachableDefinitions: true,
const schemaInput = new JSONSchemaInput(undefined);
await schemaInput.addSource({
name: "AWS",
schema: JSON.stringify(this.schema),
});
const inputData = new InputData();
inputData.addInput(schemaInput);

const { lines: serverlessTs } = await quicktype({
inputData,
lang: "typescript",
rendererOptions: {
"just-types": "true",
},
});
fs.writeFileSync("index.d.ts", compiledDefinitions);
}
}

const replaceAllConstForEnum = (schema: JSONSchema4): JSONSchema4 => {
if ("object" !== typeof schema) {
return schema;
writeFileSync("index.d.ts", serverlessTs.join("\n"));
}

return Object.fromEntries(
Object.entries(schema).map(([key, value]) => {
if (key === "const") {
return ["enum", [value]];
}

if (Array.isArray(value)) {
return [key, value.map(replaceAllConstForEnum)];
}

if ("object" === typeof value && value !== null) {
return [key, replaceAllConstForEnum(value)];
}

return [key, value];
})
);
};
}

module.exports = ConfigSchemaHandlerTypescriptDefinitionsPlugin;

0 comments on commit 5fced12

Please sign in to comment.