EntityGraphQL / EntityGraphQL

A GraphQL library for .NET
https://entitygraphql.github.io/
MIT License
417 stars 54 forks source link

Add Variables in filter Query #396

Open santhidhanuskodi23 opened 3 months ago

santhidhanuskodi23 commented 3 months ago

Hi,

I would like to know how I can I implement variables passing to the query. An example query below

query GetClientsByName($clientName: string){ clients(filter: "clientName == $clientName")
{ hasNextPage hasPreviousPage items { clientCode clientName } totalItems } }

I have written a very simple wrapper .net core api using entity graphql. services.AddGraphQLSchema(provider => { provider.OnFieldCreated = (field) => { if (field.ReturnType.IsList && field.ReturnType.SchemaType.GqlType == GqlTypes.QueryObject && !field.FromType.IsInterface) { field.UseFilter().UseSort().UseOffsetPaging(defaultPageSize: DefaultPageSize, maxPageSize: MaxPages); } }; });

How Can I modify the current app to include variables support? Any sample application or google links?

lukemurray commented 3 months ago

The filter extension doesn't support GraphQL variables (it probably could in the future). You're options are make the whole filter string a variable or use a different method.

query GetClientsByName($filter: string){
clients(filter: $filter)
{
hasNextPage
hasPreviousPage
items {
clientCode
clientName
}
totalItems
}
}

And then call it with $filter set to the whole string e.g. clientName == "Barry"

Or you you just want to filter on clientName you could implement the field like so

schema.Query().ReplaceField("clients",
    new {
        clientName = (string?)null
    },
    (ctx, args) => ctx.Clients.WhereWhen(c => c.ClientName == args.clientName.Value, !string.IsNullOrEmpty(args.clientName.Value),
    "Get clients, optionally filtered by client name");

Then you query just takes clientName argument

query GetClientsByName($clientName: string){
clients(clientName: $clientName)
{
hasNextPage
hasPreviousPage
items {
clientCode
clientName
}
totalItems
}
}