Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed unquoted numeric enum identifiers #4932

Merged
merged 1 commit into from
Oct 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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