繁体   English   中英

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

[英]In GraphQL HotChocolate can you have optional parameters or use a constructor?

我将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属性使用此逻辑,但文档(在我看来)尚不清楚,谁能对此有所了解?

谢谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM