| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- import { PluginFunction } from '@graphql-codegen/plugin-helpers';
- import { buildScalars } from '@graphql-codegen/visitor-plugin-common';
- import {
- FieldDefinitionNode,
- GraphQLFieldMap,
- GraphQLNamedType,
- GraphQLObjectType,
- GraphQLSchema,
- GraphQLType,
- GraphQLUnionType,
- InterfaceTypeDefinitionNode,
- isNamedType,
- isObjectType,
- isTypeDefinitionNode,
- isUnionType,
- NonNullTypeNode,
- ObjectTypeDefinitionNode,
- parse,
- printSchema,
- UnionTypeDefinitionNode,
- visit,
- Visitor,
- } from 'graphql';
- // This plugin generates classes for all GraphQL types which implement the `ErrorResult` interface.
- // This means that when returning an error result from a GraphQL operation, you can use one of
- // the generated classes rather than constructing the object by hand.
- // It also generates type resolvers to be used by Apollo Server to discriminate between
- // members of returned union types.
- export const ERROR_INTERFACE_NAME = 'ErrorResult';
- const empty = () => '';
- const errorsVisitor: Visitor<any> = {
- NonNullType(node: NonNullTypeNode): string {
- return node.type.kind === 'NamedType' ? node.type.name.value : '';
- },
- FieldDefinition(node: FieldDefinitionNode): string {
- return ` ${node.name.value}: Scalars['${node.type}']`;
- },
- ScalarTypeDefinition: empty,
- InputObjectTypeDefinition: empty,
- EnumTypeDefinition: empty,
- UnionTypeDefinition: empty,
- InterfaceTypeDefinition(node: InterfaceTypeDefinitionNode) {
- if (node.name.value !== ERROR_INTERFACE_NAME) {
- return '';
- }
- return [
- `export class ${ERROR_INTERFACE_NAME} {`,
- ` readonly __typename: string;`,
- ` readonly code: ErrorCode;`,
- ...node.fields.filter(f => !(f as any).includes('code:')).map(f => `${f};`),
- `}`,
- ].join('\n');
- },
- ObjectTypeDefinition(
- node: ObjectTypeDefinitionNode,
- key: number | string | undefined,
- parent: any,
- ): string {
- if (!inheritsFromErrorResult(node)) {
- return '';
- }
- const originalNode = parent[key] as ObjectTypeDefinitionNode;
- return [
- `export class ${node.name.value} extends ${ERROR_INTERFACE_NAME} {`,
- ` readonly __typename = '${node.name.value}';`,
- ` readonly code = ErrorCode.${node.name.value};`,
- ` constructor(`,
- ...node.fields.filter(f => !(f as any).includes('code:')).map(f => ` public ${f},`),
- ` ) {`,
- ` super();`,
- ` }`,
- `}`,
- ].join('\n');
- },
- };
- export const plugin: PluginFunction<any> = (schema, documents, config, info) => {
- const printedSchema = printSchema(schema); // Returns a string representation of the schema
- const astNode = parse(printedSchema); // Transforms the string into ASTNode
- const result = visit(astNode, { leave: errorsVisitor });
- const defs = result.definitions.filter(d => !!d);
- return {
- content: [
- `/** This file was generated by the graphql-errors-plugin, which is part of the "codegen" npm script. */`,
- `import { ErrorCode } from '@vendure/common/lib/generated-types';`,
- generateScalars(schema, config),
- ...defs,
- defs.length ? generateIsErrorFunction(schema) : '',
- generateTypeResolvers(schema),
- ].join('\n\n'),
- };
- };
- function generateScalars(schema: GraphQLSchema, config: any): string {
- const scalarMap = buildScalars(schema, config.scalars);
- const allScalars = Object.keys(scalarMap)
- .map(scalarName => {
- const scalarValue = scalarMap[scalarName].type;
- const scalarType = schema.getType(scalarName);
- return ` ${scalarName}: ${scalarValue};`;
- })
- .join('\n');
- return `export type Scalars = {\n${allScalars}\n};`;
- }
- function generateErrorClassSource(node: ObjectTypeDefinitionNode) {
- let source = `export class ${node.name.value} {`;
- for (const field of node.fields) {
- source += ` ${1}`;
- }
- }
- function generateIsErrorFunction(schema: GraphQLSchema) {
- const errorNodes = Object.values(schema.getTypeMap())
- .map(type => type.astNode)
- .filter(isObjectTypeDefinition)
- .filter(node => inheritsFromErrorResult(node));
- return `
- const errorTypeNames = new Set([${errorNodes.map(n => `'${n.name.value}'`).join(', ')}]);
- export function isGraphQLError(input: any): input is import('@vendure/common/lib/generated-types').${ERROR_INTERFACE_NAME} {
- return input instanceof ${ERROR_INTERFACE_NAME} || errorTypeNames.has(input.__typename);
- }`;
- }
- function generateTypeResolvers(schema: GraphQLSchema) {
- const mutations = getOperationsThatReturnErrorUnions(schema, schema.getMutationType().getFields());
- const queries = getOperationsThatReturnErrorUnions(schema, schema.getQueryType().getFields());
- const operations = [...mutations, ...queries];
- const isAdminApi = !!schema.getType('UpdateGlobalSettingsInput');
- const varName = isAdminApi ? `adminErrorOperationTypeResolvers` : `shopErrorOperationTypeResolvers`;
- const result = [`export const ${varName} = {`];
- for (const operation of operations) {
- const returnType = unwrapType(operation.type) as GraphQLUnionType;
- const nonErrorResult = returnType.getTypes().find(t => !inheritsFromErrorResult(t));
- result.push(
- ` ${returnType.name}: {`,
- ` __resolveType(value: any) {`,
- // tslint:disable-next-line:no-non-null-assertion
- ` return isGraphQLError(value) ? (value as any).__typename : '${nonErrorResult!.name}';`,
- ` },`,
- ` },`,
- );
- }
- result.push(`};`);
- return result.join('\n');
- }
- function getOperationsThatReturnErrorUnions(schema: GraphQLSchema, fields: GraphQLFieldMap<any, any>) {
- return Object.values(fields).filter(operation => {
- const innerType = unwrapType(operation.type);
- if (innerType.astNode?.kind === 'UnionTypeDefinition') {
- return isUnionOfResultAndErrors(schema, innerType.astNode);
- }
- return false;
- });
- }
- function isUnionOfResultAndErrors(schema: GraphQLSchema, node: UnionTypeDefinitionNode) {
- const errorResultTypes = node.types.filter(namedType => {
- const type = schema.getType(namedType.name.value);
- if (isObjectType(type)) {
- if (inheritsFromErrorResult(type)) {
- return true;
- }
- }
- return false;
- });
- return (errorResultTypes.length = node.types.length - 1);
- }
- function isObjectTypeDefinition(node: any): node is ObjectTypeDefinitionNode {
- return node && isTypeDefinitionNode(node) && node.kind === 'ObjectTypeDefinition';
- }
- function inheritsFromErrorResult(node: ObjectTypeDefinitionNode | GraphQLObjectType): boolean {
- const interfaceNames = isObjectType(node)
- ? node.getInterfaces().map(i => i.name)
- : node.interfaces.map(i => i.name.value);
- return interfaceNames.includes(ERROR_INTERFACE_NAME);
- }
- /**
- * Unwraps the inner type from a higher-order type, e.g. [Address!]! => Address
- */
- function unwrapType(type: GraphQLType): GraphQLNamedType {
- if (isNamedType(type)) {
- return type;
- }
- let innerType = type;
- while (!isNamedType(innerType)) {
- innerType = innerType.ofType;
- }
- return innerType;
- }
|