Skip to content

Commit

Permalink
feat: load entry union type name automatically
Browse files Browse the repository at this point in the history
  • Loading branch information
laurci committed Sep 4, 2021
1 parent 637ab44 commit 73de08a
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
3 changes: 3 additions & 0 deletions schemas/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"entry": {
"type": "string"
},
"entryTypeName": {
"type": "string"
},
"exclude": {
"items": {
"type": "string"
Expand Down
20 changes: 17 additions & 3 deletions src/cli/commands/generate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type Yargs from "yargs";
import * as fs from "fs";
import * as path from "path";
import {Project, InterfaceDeclaration} from "ts-morph";
import {Project, InterfaceDeclaration, SourceFile} from "ts-morph";
import * as TJS from "typescript-json-schema";
import {makeLogger} from "../../log";
import config, {Config} from "../config";
Expand All @@ -20,6 +20,16 @@ type ResourcesMeta = Config["resources"] & {
};
};

function findEntryTypeName(sourceFile: SourceFile): string {
const types = sourceFile.getTypeAliases();
for (let t of types) {
if (t.isExported() && t.getType().isUnion()) {
return t.getName();
}
}
throw new Error("No exported union type alias found");
}

export const generateCommand = (yargs: typeof Yargs) => {
return yargs.command(
"generate",
Expand All @@ -40,7 +50,11 @@ export const generateCommand = (yargs: typeof Yargs) => {

const dependenciesMap: {[key: string]: InterfaceDeclaration} = {};

const mainType = mainSource.getTypeAliasOrThrow("Services").getType();
const typeAliasName = config.resources?.entryTypeName ?? findEntryTypeName(mainSource);

log.info("Using exported type", typeAliasName);

const mainType = mainSource.getTypeAliasOrThrow(typeAliasName).getType();

const declaredServices = (
mainType.isUnion()
Expand Down Expand Up @@ -86,7 +100,7 @@ export const generateCommand = (yargs: typeof Yargs) => {
const program = TJS.getProgramFromFiles(project.getSourceFiles().map((x) => x.getFilePath()));

log.debug("generating schema");
let schema = TJS.generateSchema(program, "Services", {
let schema = TJS.generateSchema(program, typeAliasName, {
excludePrivate: true,
propOrder: true,
ignoreErrors: true,
Expand Down
1 change: 1 addition & 0 deletions src/cli/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export interface Config {
[name: string]: string;
};
resources?: {
entryTypeName?: string;
include?: string;
exclude?: string[];
output: ConfigOutputs;
Expand Down

0 comments on commit 73de08a

Please sign in to comment.