简体   繁体   中英

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

I am using HotChocolate as a GraphQL server from my ASP.NET Core Api . The parameters of a request need to have an optional parameter, a Guid, however if the Guid is null then the model needs to generate a random Guid.

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

The class Mutation has the following method.

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

The ActionCommand class looks like this:

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()
  }
}

This command is the problem in question. I want to be able to use this logic for the Id property in GraphQL, the documentation isn't clear (to my eyes), can anyone shed some light on this?

Thanks!

The solution to this problem was creating an abstract base CommandType like so:

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

Then have the custom Input types inherit this class like so:

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

Or the short hand if no further configuring is needed.

public class SpecificCommandType : CommandType<SpecificCommand> { }

The commands themselves derive from the Command class which generates a Guid for the values as needed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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