Skip to content

Commit

Permalink
feat(cli): import - support enum string fields (#210)
Browse files Browse the repository at this point in the history
When a JSON schema includes an `enum` string value list, generate a typescript `enum` to offer usability.

Resolves #196

BREAKING CHANGE: enum string values are now proper enums instead of just `string`s.

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
Elad Ben-Israel authored May 27, 2020
1 parent b37b105 commit 8b8ad44
Show file tree
Hide file tree
Showing 6 changed files with 1,976 additions and 1,666 deletions.
38 changes: 38 additions & 0 deletions packages/cdk8s-cli/lib/import/type-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ export class TypeGenerator {
return 'Date';
}

if (Array.isArray(def.enum) && def.enum.length > 0 && !def.enum.find(x => typeof(x) !== 'string')) {
return this.emitEnum(typeName, def, structFqn);
}

return 'string';
}

Expand Down Expand Up @@ -258,6 +262,40 @@ export class TypeGenerator {
code.line();
}

private emitEnum(typeName: string, def: JSONSchema4, structFqn: string) {

this.emitLater(typeName, code => {

if (!def.enum || def.enum.length === 0) {
throw new Error(`definition is not an enum: ${JSON.stringify(def)}`);
}

if (def.type !== 'string') {
throw new Error(`can only generate string enums`);
}

this.emitDescription(code, structFqn, def.description);

code.openBlock(`export enum ${typeName}`);

for (const value of def.enum) {
if (typeof(value) !== 'string') {
throw new Error(`can only generate enums for string values`);
}

// sluggify and turn to UPPER_SNAKE_CASE
const memberName = code.toSnakeCase(value.replace(/[^a-z0-9]/gi, '_')).split('_').filter(x => x).join('_').toUpperCase();

code.line(`/** ${value} */`);
code.line(`${memberName} = "${value}",`);
}

code.closeBlock();
});

return typeName;
}

private emitDescription(code: CodeMaker, fqn: string, description?: string, annotations: { [type: string]: string } = { }) {
code.line('/**');

Expand Down
Loading

0 comments on commit 8b8ad44

Please sign in to comment.