You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 __resolveType method uses property checks to identify which type is being returned—make sure your Cat and GraphQLError types have unique properties to avoid ambiguity.
  • Wrap your service calls in try/catch blocks to return a GraphQLError object when something goes wrong, and the Cat object on successful operations.
  • If you prefer cleaner separation of concerns, you can create a dedicated resolver for the MutationResult union 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:22:15