我正在将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属性使用此逻辑,但文档(在我看来)尚不清楚,任何人都可以对此有所了解吗?
谢谢!
答案 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; }
}