在GraphQL HotChocolate中,您可以使用可选参数还是使用构造函数?

时间:2019-07-11 18:52:17

标签: c# graphql hotchocolate

我正在将GraphQL中的HotChocolate用作ASP.NET Core Api服务器。请求的参数需要具有可选参数Guid,但是,如果Guid为空,则模型需要生成随机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属性使用此逻辑,但文档(在我看来)尚不清楚,任何人都可以对此有所了解吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

解决此问题的方法是创建一个抽象的基本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();
  }
}

然后使自定义Input类型像这样继承此类:

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; }
}