GraphQL How would I write a query to find by first name

后端 未结 1 1741
野的像风
野的像风 2021-01-23 11:02

I am trying to understand Graph QL and have a basic example working. e.g. if I pass in this query I get back the match with the id.

query {
  person(id:\"4090D8F         


        
相关标签:
1条回答
  • 2021-01-23 11:38

    You would need to either change the field you have here to make the id parameter optional or create a new field (maybe called persons or people) and add a new parameter that you parse into your data repository. Personally, I would favour doing the latter and create a new field. For example:

    public PersonQuery(ShoppingData data)
    {
        Field<PersonType>( /* snip */ );
    
        //Note this is now returning a list of persons
        Field<ListGraphType<PersonType>>(
            "people", //The new field name
            description: "A list of people",
            arguments: new QueryArguments(
                new QueryArgument<NonNullGraphType<StringGraphType>>
                {
                    Name = "firstName", //The parameter to filter on first name
                    Description = "The first name of the person"
                }),
            resolve: ctx =>
            {
                //You will need to write this new method
                return data.GetByFirstName(ctx.GetArgument<string>("firstName"));
            });
    }
    

    And now you just need to write the GetByFirstName method yourself. The query would now look like this:

    query {
      people(firstName:"Andrew")
      {
        firstname
        surname
      }
    }
    

    Now you may find that GetByFirstName isn't enough and you also want a surname parameter too, and for them to be optional, so you could do something like this:

    Field<ListGraphType<PersonType>>(
        "people",
        description: "A list of people",
        arguments: new QueryArguments(
            new QueryArgument<StringGraphType>
            {
                Name = "firstName", //The parameter to filter on first name
                Description = "The first name of the person"
            },
            new QueryArgument<StringGraphType>
            {
                Name = "surname",
                Description = "The surname of the person"
            }),
        resolve: ctx =>
        {
            //You will need to write this new method
            return data.SearchPeople(
                ctx.GetArgument<string>("firstName"), 
                ctx.GetArgument<string>("surame"));
        });
    
    0 讨论(0)
提交回复
热议问题