Skip to content

Commit

Permalink
swap ref if there is a default
Browse files Browse the repository at this point in the history
  • Loading branch information
inferrinizzard committed Apr 4, 2024
1 parent 3f377f8 commit f30f1c2
Showing 1 changed file with 20 additions and 16 deletions.
36 changes: 20 additions & 16 deletions packages/quicktype-typescript-input/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as ts from "typescript";
import { PartialArgs, generateSchema } from "@mark.probst/typescript-json-schema";
import { PartialArgs, generateSchema } from "typescript-json-schema";

import { defined, JSONSchemaSourceData, messageError } from "quicktype-core";

Expand Down Expand Up @@ -35,7 +35,24 @@ export function schemaForTypeScriptSources(sourceFileNames: string[]): JSONSchem

const schema = generateSchema(program, "*", settings);
const uris: string[] = [];
let topLevelName: string | undefined = undefined;
let topLevelName: string = "";

// if there is a type that is `export default`, swap the corresponding ref
if (schema?.definitions?.default) {
const defaultDefinition = schema?.definitions?.default;
const matchingDefaultName = Object.entries(schema?.definitions ?? {}).find(
([_name, definition]) => (definition as Record<string, unknown>)["$ref"] === "#/definitions/default"
)?.[0];

if (matchingDefaultName) {
topLevelName = matchingDefaultName;
(defaultDefinition as Record<string, unknown>).title = topLevelName;

schema.definitions[matchingDefaultName] = defaultDefinition;
schema.definitions.default = { $ref: `#/definitions/${matchingDefaultName}` };
}
}

if (schema !== null && typeof schema === "object" && typeof schema.definitions === "object") {
for (const name of Object.getOwnPropertyNames(schema.definitions)) {
const definition = schema.definitions[name];
Expand All @@ -59,31 +76,18 @@ export function schemaForTypeScriptSources(sourceFileNames: string[]): JSONSchem

uris.push(`#/definitions/${name}`);

if (topLevelName === undefined) {
if (!topLevelName) {
if (typeof definition.title === "string") {
topLevelName = definition.title;
} else {
topLevelName = name;
}
} else {
topLevelName = "";
}
}
}
if (uris.length === 0) {
uris.push("#/definitions/");
}
if (topLevelName === undefined) {
topLevelName = "";
}
if (topLevelName === "default") {
const matchingDefaultName = Object.entries(schema?.definitions ?? {}).find(
([_name, definition]) => (definition as Record<string, unknown>)["$ref"] === "#/definitions/default"
)?.[0];

if (matchingDefaultName) {
topLevelName = matchingDefaultName;
}
}
return { schema: JSON.stringify(schema), name: topLevelName, uris, isConverted: true };
}

0 comments on commit f30f1c2

Please sign in to comment.