In GraphQL type definitions, each field can take zero or more arguments. Every argument passed to a field needs to have a name and a type. Next to this, it’s also possible to specify default values for arguments.
For example, let’s create a query in our schema that returns all products for a category, if no category is specified we want to return ‘Beverages’:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Query { | |
allProducts(category:String="Beverages"): [Product!]! | |
} |
But how can you achieve this using GraphQL DotNet using the GraphType first approach?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProductsQuery: ObjectGraphType<object> | |
{ | |
private readonly IContextProvider _contextProvider; | |
public ProductsQuery(IContextProvider contextProvider) | |
{ | |
_contextProvider = contextProvider; | |
Name = "Query"; | |
Field<NonNullGraphType<ListGraphType<ProductType>>>( | |
"allProducts", | |
arguments: new QueryArguments( | |
new QueryArgument<StringGraphType>() {Name="category", DefaultValue = "Beverages"}), | |
resolve: context => | |
{ | |
var service = _contextProvider.Get<IProductService>(); | |
return service.GetProducgts(context.GetArgument<string>("category")); | |
}); | |
} | |
} |