Skip to content

Instantly share code, notes, and snippets.

@maxymczech
Last active April 8, 2024 08:17
Show Gist options
  • Save maxymczech/b629a17df4c2e619e1ba3f45e544d1c7 to your computer and use it in GitHub Desktop.
Save maxymczech/b629a17df4c2e619e1ba3f45e544d1c7 to your computer and use it in GitHub Desktop.
GraphQL Code Generator plugin to extract all Enum type descriptions

Normally graphql-codegen will export Enum descriptions as comments, like this:

export enum GenderEnum {
  // Female person <-- this is the description
  Female = 'female',
  // Male person
  Male = 'male',
  // Other person
  Other = 'other'
}

In our use case, we needed to extract these descriptions and integrate them with our frontend i18n system. So I wrote this small graphql-codegen plugin, it extracts all Enum types from the schema and exports the descriptions:

const { isEnumType } = require('graphql');

module.exports = {
  plugin(schema, documents, config) {
    const result = [];
    const typeMap = schema.getTypeMap();
    Object.keys(typeMap).forEach(typeName => {
      if (isEnumType(typeMap[typeName])) {
        const descriptions = {};
        typeMap[typeName].getValues().forEach(item => {
          descriptions[item.name] = item.description;
        })
        result.push(`export const ${typeName}Descriptions = ${JSON.stringify(descriptions, null, 2).trim()};`);
        result.push('');
      }
    })
    return result.join('\n');
  }
};

To use the plugin, add it to your codegen.ts:

const config: CodegenConfig = {
  generates: {
    "./src/__generated__/enum-descriptions.ts": {
      plugins: ['graphql-codegen-enums-plugin.js'],
    },
  },
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment