graphql-code-generator icon indicating copy to clipboard operation
graphql-code-generator copied to clipboard

[visitor-plugin-common] parseEnumValue ignore enum mapping if name and value are the same

Open nguymin4 opened this issue 3 years ago • 1 comments

I want to to ask about this specific line of code. Basically we ignore the enum if the name and value are the same https://github.com/dotansimha/graphql-code-generator/blob/e947f8e393e04dfd52f78bbb35b7e3e6af825c4f/packages/plugins/other/visitor-plugin-common/src/enum-values.ts#L27

For example in the test code below HR is excluded from mappedValues although I think this is a valid use case. I tried to remove the check but it affected other part of the code base. Do you have any suggestions how we can support the use case where enum value and enum name are the same? Thanks. Notes: At the moment my work around is changing the enum name from HR to HUMAN_RESOURCE ...

  const schemaWithEnumValues = new GraphQLSchema({
    query: new GraphQLObjectType({
      name: 'Query',
      fields: {
        department: {
          type: new GraphQLEnumType({
            name: 'Department',
            values: {
              HR: {
                value: 'HR',
              },
              FINANCE: {
                value: 'Finance',
              },
            },
          }),
        },
      },
    }),
  });

  it('should respect enum values from schema and escape it if needed', () => {
    const result = parseEnumValues({
      schema: schemaWithEnumValues,
      mapOrStr: {},
      ignoreEnumValuesFromSchema: false,
    });

    expect(result).toEqual({
      Department: {
        isDefault: false,
        typeIdentifier: 'Department',
        sourceFile: null,
        importIdentifier: null,
        sourceIdentifier: null,
        mappedValues: {
          FINANCE: 'Finance',
        },
      },
    });
  });

nguymin4 avatar Mar 18 '21 15:03 nguymin4

This is maybe a use case to make the change. In my app, we have some enums where we need to remap the enum where in others we do not need to remap. Example:

export const exampleTypedef = gql`
  enum Example {
    A
    B
    C
  }
`;

export const exampleResolver: Resolvers = {
  Example: {
    A: 'A',
    B: 'Banana',
    C: 'C',
  },
};

Trying to secure the resolver definitions to ensure all the keys are appropriately mapped, yields the following type error: image

There's an argument to be had that we should just omit the enum value remapping from the resolvers as it's redundant though.

dustinsgoodman avatar Aug 29 '22 18:08 dustinsgoodman