簡體   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