How do I access the argument values in GraphQL fields when using GraphQL.Net with c#?

1k views Asked by At

Consider the following query;

query {
  droid(id: "123") {
    id
    name
  }
}

I can access the id query argument on the server when using GraphQL.net like this;

public class Droid
{
  public string Id { get; set; }
  public string Name { get; set; }
}

public class DroidType : ObjectGraphType
{
  public DroidType()
  {
    Field<NonNullGraphType<IdGraphType>>("id");
    Field<StringGraphType>("name");
  }
}

public class StarWarsQuery : ObjectGraphType
{
  private List<Droid> _droids = new List<Droid>
  {
    new Droid { Id = "123", Name = "R2-D2" }
  };

  public StarWarsQuery()
  {
    Field<DroidType>(
      "droid",
      arguments: new QueryArguments(
        new QueryArgument<IdGraphType> { Name = "id" }
      ),
      resolve: context =>
      {
        var id = context.GetArgument<string>("id");//<---- THIS
        return _droids.FirstOrDefault(x => x.Id == id);
      }
    );
  }
}

But how would I handle a query like this;

query {
  droid(id: "123") {
    id
    name
    owner(id: "456") {
      id
      name
    }
  }
}

Its not a great example, but what I would expect would be to create an OwnerType and add a new field to my DriodType;

public class DroidType : ObjectGraphType
{
  public DroidType()
  {
    Field<NonNullGraphType<IdGraphType>>("id");
    Field<StringGraphType>("name");
    Field<OwnerType>(
      "owner",
      arguments: new QueryArguments(
        new QueryArgument<IdGraphType> { Name = "id" }
      ),
      resolve: context =>
      {
        var id = context.GetArgument<string>("id");
        return _owners.FirstOrDefault(x => x.Id == id);
      }
    );
  }
}

Here is my issue, I only want the owner with an ID of 456 if the driod with an ID of 123 has been owned by them. To do this I would need to filter the owners to only include those that had owned droid 123. To do that I need to be able to access the id of the droid from within the owner field of the DroidType i.e. I'd want to access the argument value of the droid field in StarWarsQuery from the owner field on the DroidType. How would I do this?

1

There are 1 answers

0
mark_h On

The context in the resolve arguement for the owner field has a "Source" property, this holds information on the droid type. I was able to get the information I needed from there