【问题标题】:In GraphQL HotChocolate can you have optional parameters or use a constructor?在 GraphQL HotChocolate 中你可以有可选参数或使用构造函数吗?
【发布时间】:2019-11-21 13:17:44
【问题描述】:

我正在使用HotChocolate 作为我的ASP.NET Core ApiGraphQL 服务器。请求的参数需要有一个可选参数 Guid,但是如果 Guid 为 null,则模型需要生成一个随机 Guid。

public class MutationType : ObjectType<Mutation> {
  protected override void Configure(IObjectTypeDescriptor<Mutation> desc) 
  {
    desc
      .Field((f) => f.CreateAction(default))
      .Name("createAction");
  }
}

Mutation 类有如下方法。

public ActionCommand CreateAction(ActionCommand command) {
  ...
  return command;
}

ActionCommand 类如下所示:

public class ActionCommand {
  public Guid Id { get; set; }
  public string Name { get; set; }

  public ActionCommand(string name, Guid id = null) {
    Name = name;
    Id = id ?? Guid.NewGuid()
  }
}

这个命令就是问题所在。我希望能够将此逻辑用于 GraphQL 中的 Id 属性,文档不清楚(在我看来),任何人都可以对此有所了解吗?

谢谢!

【问题讨论】:

  • 在这种情况下,您的命令是一个输入对象和一个输出对象,并且您确实想在未提供对象时生成一个新的 Guid?
  • 嗨,迈克尔,我找到了解决方案,我将把它作为答案发布,谢谢!另一个问题,我正在尝试使用“URLType”作为输入,但它说“www.google.com”与类型不匹配,我做错了什么吗?

标签: c# graphql hotchocolate


【解决方案1】:

解决这个问题的方法是创建一个抽象的基本 CommandType,如下所示:

public abstract class CommandType<TCommand> : InputObjectType<TCommand> 
    where TCommand : Command {
  protected override void Configure(IInputObjectTypeDescriptor<TCommand> desc) {
    desc.Field(f => f.CausationId).Ignore();
    desc.Field(f => f.CorrelationId).Ignore();
  }
}

然后让自定义输入类型像这样继承这个类:

public class SpecificCommandType : CommandType<SpecificCommand> {
   protected override void Configure(IInputObjectTypeDescriptor<SpecificCommand> desc) {
      base.Configure(desc);
      desc.Field(t => t.Website).Type<NonNullType<UrlType>>();
   }
}

如果不需要进一步配置,也可以使用简写。

public class SpecificCommandType : CommandType<SpecificCommand> { }

命令本身派生自 Command 类,该类根据需要为值生成 Guid。

public abstract class Command {
  protected Command(Guid? correlationId = null, Guid? causationId = null) {
    this.CausationId = this.CorrelationId = Guid.NewGuid();
  }

  public Guid CausationId { get; set; }
  public Guid CorrelationId { get; set; }
}

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多