graphql-errors-plugin.ts 9.3 KB

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