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'],
},
},
};