generate-error-code-enum.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import { buildSchema, extendSchema, GraphQLSchema, parse } from 'graphql';
  2. export const ERROR_INTERFACE_NAME = 'ErrorResult';
  3. /**
  4. * Generates the members of the `ErrorCode` enum dynamically, by getting the names of
  5. * all the types which inherit from the `ErrorResult` interface.
  6. */
  7. export function generateErrorCodeEnum(typeDefsOrSchema: string | GraphQLSchema): GraphQLSchema {
  8. const schema = typeof typeDefsOrSchema === 'string' ? buildSchema(typeDefsOrSchema) : typeDefsOrSchema;
  9. const errorNodes = Object.values(schema.getTypeMap())
  10. .map(type => type.astNode)
  11. .filter(node => {
  12. return (
  13. node &&
  14. node?.kind === 'ObjectTypeDefinition' &&
  15. node.interfaces?.map(i => i.name.value).includes(ERROR_INTERFACE_NAME)
  16. );
  17. });
  18. if (!errorNodes.length) {
  19. return schema;
  20. }
  21. const errorCodeEnum = `
  22. extend enum ErrorCode {
  23. ${errorNodes.map(n => camelToUpperSnakeCase(n?.name.value || '')).join('\n')}
  24. }`;
  25. return extendSchema(schema, parse(errorCodeEnum));
  26. }
  27. function camelToUpperSnakeCase(input: string): string {
  28. return input.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
  29. }