graphql-errors-plugin.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import { PluginFunction } from '@graphql-codegen/plugin-helpers';
  2. import { buildScalars } from '@graphql-codegen/visitor-plugin-common';
  3. import {
  4. FieldDefinitionNode,
  5. GraphQLFieldMap,
  6. GraphQLNamedType,
  7. GraphQLObjectType,
  8. GraphQLSchema,
  9. GraphQLType,
  10. GraphQLUnionType,
  11. InterfaceTypeDefinitionNode,
  12. isNamedType,
  13. isObjectType,
  14. isTypeDefinitionNode,
  15. isUnionType,
  16. NonNullTypeNode,
  17. ObjectTypeDefinitionNode,
  18. parse,
  19. printSchema,
  20. UnionTypeDefinitionNode,
  21. visit,
  22. Visitor,
  23. ListTypeNode,
  24. } from 'graphql';
  25. // This plugin generates classes for all GraphQL types which implement the `ErrorResult` interface.
  26. // This means that when returning an error result from a GraphQL operation, you can use one of
  27. // the generated classes rather than constructing the object by hand.
  28. // It also generates type resolvers to be used by Apollo Server to discriminate between
  29. // members of returned union types.
  30. export const ERROR_INTERFACE_NAME = 'ErrorResult';
  31. const empty = () => '';
  32. const errorsVisitor: Visitor<any> = {
  33. NonNullType(node: NonNullTypeNode): string | ListTypeNode {
  34. return node.type.kind === 'NamedType'
  35. ? node.type.name.value
  36. : node.type.kind === 'ListType'
  37. ? node.type
  38. : '';
  39. },
  40. FieldDefinition(node: FieldDefinitionNode): string {
  41. const scalarType = node.type.kind === 'ListType' ? node.type.type : node.type;
  42. const listPart = node.type.kind === 'ListType' ? `[]` : ``;
  43. return ` ${node.name.value}: Scalars['${scalarType}']${listPart}`;
  44. },
  45. ScalarTypeDefinition: empty,
  46. InputObjectTypeDefinition: empty,
  47. EnumTypeDefinition: empty,
  48. UnionTypeDefinition: empty,
  49. InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {
  50. if (node.name.value !== ERROR_INTERFACE_NAME) {
  51. return '';
  52. }
  53. return [
  54. `export class ${ERROR_INTERFACE_NAME} {`,
  55. ` readonly __typename: string;`,
  56. ` readonly errorCode: string;`,
  57. ...node.fields.filter(f => !(f as any).includes('errorCode:')).map(f => `${f};`),
  58. `}`,
  59. ].join('\n');
  60. },
  61. ObjectTypeDefinition(
  62. node: ObjectTypeDefinitionNode,
  63. key: number | string | undefined,
  64. parent: any,
  65. ): string {
  66. if (!inheritsFromErrorResult(node)) {
  67. return '';
  68. }
  69. const originalNode = parent[key] as ObjectTypeDefinitionNode;
  70. return [
  71. `export class ${node.name.value} extends ${ERROR_INTERFACE_NAME} {`,
  72. ` readonly __typename = '${node.name.value}';`,
  73. // We cast this to "any" otherwise we need to specify it as type "ErrorCode",
  74. // which means shared ErrorResult classes e.g. OrderStateTransitionError
  75. // will not be compatible between the admin and shop variations.
  76. ` readonly errorCode = '${camelToUpperSnakeCase(node.name.value)}' as any;`,
  77. ` readonly message = '${camelToUpperSnakeCase(node.name.value)}';`,
  78. ` constructor(`,
  79. ...node.fields
  80. .filter(f => !(f as any).includes('errorCode:') && !(f as any).includes('message:'))
  81. .map(f => ` public ${f},`),
  82. ` ) {`,
  83. ` super();`,
  84. ` }`,
  85. `}`,
  86. ].join('\n');
  87. },
  88. };
  89. export const plugin: PluginFunction<any> = (schema, documents, config, info) => {
  90. const printedSchema = printSchema(schema); // Returns a string representation of the schema
  91. const astNode = parse(printedSchema); // Transforms the string into ASTNode
  92. const result = visit(astNode, { leave: errorsVisitor });
  93. const defs = result.definitions
  94. .filter(d => !!d)
  95. // Ensure the ErrorResult base class is first
  96. .sort((a, b) => (a.includes('class ErrorResult') ? -1 : 1));
  97. return {
  98. content: [
  99. `/** This file was generated by the graphql-errors-plugin, which is part of the "codegen" npm script. */`,
  100. generateScalars(schema, config),
  101. ...defs,
  102. defs.length ? generateIsErrorFunction(schema) : '',
  103. generateTypeResolvers(schema),
  104. ].join('\n\n'),
  105. };
  106. };
  107. function generateScalars(schema: GraphQLSchema, config: any): string {
  108. const scalarMap = buildScalars(schema, config.scalars);
  109. const allScalars = Object.keys(scalarMap)
  110. .map(scalarName => {
  111. const scalarValue = scalarMap[scalarName].type;
  112. const scalarType = schema.getType(scalarName);
  113. return ` ${scalarName}: ${scalarValue};`;
  114. })
  115. .join('\n');
  116. return `export type Scalars = {\n${allScalars}\n};`;
  117. }
  118. function generateErrorClassSource(node: ObjectTypeDefinitionNode) {
  119. let source = `export class ${node.name.value} {`;
  120. for (const field of node.fields) {
  121. source += ` ${1}`;
  122. }
  123. }
  124. function generateIsErrorFunction(schema: GraphQLSchema) {
  125. const errorNodes = Object.values(schema.getTypeMap())
  126. .map(type => type.astNode)
  127. .filter(isObjectTypeDefinition)
  128. .filter(node => inheritsFromErrorResult(node));
  129. return `
  130. const errorTypeNames = new Set([${errorNodes.map(n => `'${n.name.value}'`).join(', ')}]);
  131. function isGraphQLError(input: any): input is import('@vendure/common/lib/generated-types').${ERROR_INTERFACE_NAME} {
  132. return input instanceof ${ERROR_INTERFACE_NAME} || errorTypeNames.has(input.__typename);
  133. }`;
  134. }
  135. function generateTypeResolvers(schema: GraphQLSchema) {
  136. const mutations = getOperationsThatReturnErrorUnions(schema, schema.getMutationType().getFields());
  137. const queries = getOperationsThatReturnErrorUnions(schema, schema.getQueryType().getFields());
  138. const operations = [...mutations, ...queries];
  139. const varName = isAdminApi(schema)
  140. ? `adminErrorOperationTypeResolvers`
  141. : `shopErrorOperationTypeResolvers`;
  142. const result = [`export const ${varName} = {`];
  143. const typesHandled = new Set<string>();
  144. for (const operation of operations) {
  145. const returnType = unwrapType(operation.type) as GraphQLUnionType;
  146. if (!typesHandled.has(returnType.name)) {
  147. typesHandled.add(returnType.name);
  148. const nonErrorResult = returnType.getTypes().find(t => !inheritsFromErrorResult(t));
  149. result.push(
  150. ` ${returnType.name}: {`,
  151. ` __resolveType(value: any) {`,
  152. // tslint:disable-next-line:no-non-null-assertion
  153. ` return isGraphQLError(value) ? (value as any).__typename : '${nonErrorResult!.name}';`,
  154. ` },`,
  155. ` },`,
  156. );
  157. }
  158. }
  159. result.push(`};`);
  160. return result.join('\n');
  161. }
  162. function getOperationsThatReturnErrorUnions(schema: GraphQLSchema, fields: GraphQLFieldMap<any, any>) {
  163. return Object.values(fields).filter(operation => {
  164. const innerType = unwrapType(operation.type);
  165. if (innerType.astNode?.kind === 'UnionTypeDefinition') {
  166. return isUnionOfResultAndErrors(schema, innerType.astNode);
  167. }
  168. return false;
  169. });
  170. }
  171. function isUnionOfResultAndErrors(schema: GraphQLSchema, node: UnionTypeDefinitionNode) {
  172. const errorResultTypes = node.types.filter(namedType => {
  173. const type = schema.getType(namedType.name.value);
  174. if (isObjectType(type)) {
  175. if (inheritsFromErrorResult(type)) {
  176. return true;
  177. }
  178. }
  179. return false;
  180. });
  181. return (errorResultTypes.length = node.types.length - 1);
  182. }
  183. function isObjectTypeDefinition(node: any): node is ObjectTypeDefinitionNode {
  184. return node && isTypeDefinitionNode(node) && node.kind === 'ObjectTypeDefinition';
  185. }
  186. function inheritsFromErrorResult(node: ObjectTypeDefinitionNode | GraphQLObjectType): boolean {
  187. const interfaceNames = isObjectType(node)
  188. ? node.getInterfaces().map(i => i.name)
  189. : node.interfaces.map(i => i.name.value);
  190. return interfaceNames.includes(ERROR_INTERFACE_NAME);
  191. }
  192. /**
  193. * Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
  194. */
  195. function unwrapType(type: GraphQLType): GraphQLNamedType {
  196. if (isNamedType(type)) {
  197. return type;
  198. }
  199. let innerType = type;
  200. while (!isNamedType(innerType)) {
  201. innerType = innerType.ofType;
  202. }
  203. return innerType;
  204. }
  205. function isAdminApi(schema: GraphQLSchema): boolean {
  206. return !!schema.getType('UpdateGlobalSettingsInput');
  207. }
  208. function camelToUpperSnakeCase(input: string): string {
  209. return input.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
  210. }