graphql-errors-plugin.ts 8.2 KB

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