如何在GraphQL .Net GraphType First中组织多个突变?

问题描述

在GraphQL .Net中,大多数示例代码都有一个顶级突变图对象,该对象中定义了许多实际的突变。
这是来自GraphQL .NET mutations page的示例:

public class StarWaRSSchema : Schema
{
  public StarWaRSSchema(IServiceProvider provider)
    : base(provider)
  {
    Query = provider.Resolve<StarWarsQuery>();
    Mutation = provider.Resolve<StarWarsMutation>();
  }
}


public class StarWarsMutation : ObjectGraphType
{
  public StarWarsMutation(StarWarsData data)
  {
    Field<HumanType>(
      "createHuman",arguments: new QueryArguments(
        new QueryArgument<NonNullGraphType<HumanInputType>> {Name = "human"}
      ),resolve: context =>
      {
        var human = context.GetArgument<Human>("human");
        return data.AddHuman(human);
      });
  }
}

当您有1-5个突变时,这似乎还不错,但是在一些较大的项目中加班可能会导致数十个突变。尽管似乎也缺少一些组织,但将它们放在一个大类中似乎足以工作。我尝试将子突变GraphTypeObject放在父突变的字段中,但是在调用子突变时遇到了一些麻烦。也许我配置错误

这只是让我感到奇怪,当然,肯定有一个十几个突变的用户,他们可能组织了自己的突变,而不是将所有突变都放在一个顶级突变对象中。

如何在GraphQL .Net GraphType First中组织多个突变?

解决方法

https://graphql-dotnet.github.io/docs/getting-started/query-organization

您可以通过添加顶级字段将查询或变异“分组”在一起。 “技巧”是在解析器中返回一个空对象。

public class StarWarsSchema : Schema
{
  public StarWarsSchema(IServiceProvider provider)
    : base(provider)
  {
    Query = provider.Resolve<StarWarsQuery>();
    Mutation = provider.Resolve<StarWarsMutation>();
  }
}

public class StarWarsMutation : ObjectGraphType
{
  public StarWarsMutation(StarWarsData data)
  {
    Field<CharacterMutation>(
      "characters",resolve: context => new { });
  }
}

public class CharacterMutation : ObjectGraphType
{
  public CharacterMutation(StarWarsData data)
  {
    Field<HumanType>(
      "createHuman",arguments: new QueryArguments(
        new QueryArgument<NonNullGraphType<HumanInputType>> {Name = "human"}
      ),resolve: context =>
      {
        var human = context.GetArgument<Human>("human");
        return data.AddHuman(human);
      });
  }
}

这种组织体现在如何调用突变(或查询)。如果只是希望它们在外部显示为平面列表(相当于一个巨型文件),则还可以使用部分类将其分解为任意多个文件。