2

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!

Tristan Trainer
  • 2,770
  • 2
  • 17
  • 33
  • 1
    In this case your command is an input object and an output object and you do want to generate a new Guid whenever the object was not provided? – Michael Ingmar Staib Jul 18 '19 at 12:01
  • Hi Again Michael, I found the solution to this one I will post it as an answer thanks! Another question though, I'm trying to use the "URLType" for an input, but it's saying that "www.google.com" doesn't match the type, is there something I'm doing wrong? – Tristan Trainer Jul 18 '19 at 12:26

1 Answers1

1

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; }
}
Tristan Trainer
  • 2,770
  • 2
  • 17
  • 33