counterfact
Version:
Generate a TypeScript-based mock server from an OpenAPI spec in seconds — with stateful routes, hot reload, and REPL support.
50 lines (49 loc) • 1.64 kB
JavaScript
import { Coder } from "./coder.js";
function scrubSchema(schema) {
// remove properties that are not valid in JSON Schema 6 and not useful anyway
const cleaned = { ...schema };
delete cleaned["example"];
delete cleaned["xml"];
return cleaned;
}
export class SchemaCoder extends Coder {
names() {
return super.names(`${this.requirement.refUrl.split("/").at(-1)}Schema`);
}
objectSchema(script) {
const { properties, required } = this.requirement.data;
const propertyLines = Object.keys(properties ?? {}).map((name) => {
const schemaCoder = new SchemaCoder(this.requirement.select(`properties/${name}`), this.version);
return `"${name}": ${schemaCoder.write(script)}`;
});
return `
{
type: "object",
required: ${JSON.stringify(required ?? [])},
properties: { ${propertyLines.join(", ")} }
}
`;
}
arraySchema(script) {
return `{
type: "array",
items: ${new SchemaCoder(this.requirement.get("items"), this.version).write(script)}
}`;
}
typeDeclaration(_namespace, script) {
return script.importExternalType("JSONSchema6", "json-schema");
}
modulePath() {
return `types/${this.requirement.refUrl}.ts`;
}
writeCode(script) {
const { type } = this.requirement.data;
if (type === "object") {
return this.objectSchema(script);
}
if (type === "array") {
return this.arraySchema(script);
}
return JSON.stringify(scrubSchema(this.requirement.data));
}
}