Skip to content

Commit

Permalink
Fixed unquoted numeric enum identifiers (#4932)
Browse files Browse the repository at this point in the history
Co-authored-by: Borre <borre.mosch@cubonacci.com>
  • Loading branch information
borremosch and Borre committed Oct 19, 2020
1 parent d723e40 commit 92d8f87
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changeset/little-pillows-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-codegen/visitor-plugin-common': patch
'@graphql-codegen/typescript': patch
---

Fixed unquoted numeric enum identifiers
Original file line number Diff line number Diff line change
Expand Up @@ -476,14 +476,23 @@ export class BaseTypesVisitor<
return node.value;
}

protected makeValidEnumIdentifier(identifier: string): string {
if (/^[0-9]/.exec(identifier)) {
return wrapWithSingleQuotes(identifier, true);
}
return identifier;
}

protected buildEnumValuesBlock(typeName: string, values: ReadonlyArray<EnumValueDefinitionNode>): string {
const schemaEnumType: GraphQLEnumType | undefined = this._schema
? (this._schema.getType(typeName) as GraphQLEnumType)
: undefined;

return values
.map(enumOption => {
const optionName = this.convertName(enumOption, { useTypesPrefix: false, transformUnderscore: true });
const optionName = this.makeValidEnumIdentifier(
this.convertName(enumOption, { useTypesPrefix: false, transformUnderscore: true })
);
const comment = transformComment((enumOption.description as any) as string, 1);
const schemaEnumValue = schemaEnumType ? schemaEnumType.getValue(enumOption.name as any).value : undefined;
let enumValue: string | number =
Expand Down
18 changes: 18 additions & 0 deletions packages/plugins/typescript/typescript/tests/typescript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,24 @@ describe('TypeScript', () => {
expect(result.prepend[0]).toBe(`import MyEnum from './files';`);
});

it('#4834 - enum members should be quoted if numeric', async () => {
const testSchema = buildSchema(/* GraphQL */ `
enum MediaItemSizeEnum {
AXB
_1X2
_3X4
}
`);

const result = (await plugin(testSchema, [], {})) as Types.ComplexPluginOutput;

expect(result.content).toBeSimilarStringTo(`export enum MediaItemSizeEnum {
Axb = 'AXB',
'1X2' = '_1X2',
'3X4' = '_3X4'
}`);
});

it('#2976 - Issues with mapped enumValues and type prefix in args', async () => {
const testSchema = buildSchema(/* GraphQL */ `
enum MyEnum {
Expand Down

0 comments on commit 92d8f87

Please sign in to comment.