GraphQL联合类型支持问题:NestJS GraphQL模块API开发
Resolving Union Types in NestJS GraphQL for Mutation Results
You’re on the right track with extending your schema to use a MutationResult union that returns either a Cat or GraphQLError—this is a great pattern for handling success/error states cleanly in GraphQL. To make this work, you just need to implement the __resolveType function so GraphQL knows how to distinguish between the two types in the union.
Here’s how to properly add this to your CatsResolvers class:
import { Resolver, Mutation, Args, ResolveField, Parent } from '@nestjs/graphql'; import { Cat } from './cat.type'; import { GraphQLError } from './graphql-error.type'; import { CatsService } from './cats.service'; @Resolver(() => Cat) export class CatsResolvers { constructor(private readonly catsService: CatsService) {} // Create Cat mutation with error handling @Mutation(() => MutationResult) async createCat(@Args('name') name: string, @Args('age') age: number) { try { return await this.catsService.create({ name, age }); } catch (error) { return { message: error.message, errorCode: error.status ?? 500, type: error.name ?? 'UnknownError', }; } } // Delete Cat mutation with error handling @Mutation(() => MutationResult) async deleteCat(@Args('id') id: string) { try { return await this.catsService.delete(id); } catch (error) { return { message: error.message, errorCode: error.status ?? 500, type: error.name ?? 'UnknownError', }; } } // Resolver function for the MutationResult union type @ResolveField(() => String, { name: '__resolveType' }) resolveType(@Parent() result: Cat | GraphQLError): string { // Check for Cat-specific properties (adjust based on your actual Cat type) if ('id' in result && 'name' in result) { return 'Cat'; } // Check for GraphQLError-specific properties if ('errorCode' in result && 'type' in result) { return 'GraphQLError'; } // Fallback for unexpected types throw new Error('Could not resolve union type for MutationResult'); } }
Quick Tips:
- The
__resolveTypemethod uses property checks to identify which type is being returned—make sure yourCatandGraphQLErrortypes have unique properties to avoid ambiguity. - Wrap your service calls in
try/catchblocks to return aGraphQLErrorobject when something goes wrong, and theCatobject on successful operations. - If you prefer cleaner separation of concerns, you can create a dedicated resolver for the
MutationResultunion instead:
import { Resolver, ResolveField, Parent } from '@nestjs/graphql'; import { Cat } from './cat.type'; import { GraphQLError } from './graphql-error.type'; @Resolver(() => MutationResult) export class MutationResultResolver { @ResolveField(() => String, { name: '__resolveType' }) resolveType(@Parent() result: Cat | GraphQLError): string { if ('id' in result) return 'Cat'; if ('errorCode' in result) return 'GraphQLError'; throw new Error('Unknown union type'); } }
Just remember to add this dedicated resolver to your module’s providers array if you go that route.
内容的提问来源于stack exchange,提问作者Thomas Trividic
相关产品推荐
相关产品推荐

