Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/strong-jars-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-codegen/visitor-plugin-common': patch
---

Add special handling for identifiers that consist entirely of _ characters when transformUnderscore is true. This prevents _ values in GraphQL enums from being emitted without identifers in the resulting types.
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,8 @@ export interface RawTypesConfig extends RawConfig {
directiveArgumentAndInputFieldMappingTypeSuffix?: string;
}

const onlyUnderscoresPattern = /^_+$/;

export class BaseTypesVisitor<
TRawConfig extends RawTypesConfig = RawTypesConfig,
TPluginConfig extends ParsedTypesConfig = ParsedTypesConfig
Expand Down Expand Up @@ -915,7 +917,9 @@ export class BaseTypesVisitor<
const optionName = this.makeValidEnumIdentifier(
this.convertName(enumOption, {
useTypesPrefix: false,
transformUnderscore: true,
// We can only strip out the underscores if the value contains other
// characters. Otherwise we'll generate syntactically invalid code.
transformUnderscore: !onlyUnderscoresPattern.test(enumOption.name as any),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious shouldn't this be enumOption.name.value? 🙂

We've recently fixed NameNode overrides which shouldn't require as any any more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

enumOption.name.value was always undefined when I was testing.

})
);
const comment = this.getNodeComment(enumOption);
Expand Down
20 changes: 19 additions & 1 deletion packages/plugins/typescript/typescript/tests/typescript.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ describe('TypeScript', () => {
}`);
});

it('Should removed underscore from enum values', async () => {
it('Should remove underscore from enum values', async () => {
const schema = buildSchema(/* GraphQL */ `
enum MyEnum {
A_B_C
Expand All @@ -213,6 +213,24 @@ describe('TypeScript', () => {
}`);
});

it('Should leave underscores in enum values when the value is only underscores', async () => {
const schema = buildSchema(/* GraphQL */ `
enum MyEnum {
_
__
_TEST
}
`);
const result = await plugin(schema, [], {}, { outputFile: '' });

expect(result.content).toBeSimilarStringTo(`
export enum MyEnum {
_ = '_',
__ = '__',
Test = '_TEST'
}`);
});

it('Should work with enum as const', async () => {
const schema = buildSchema(/* GraphQL */ `
enum MyEnum {
Expand Down