I’m spending a lot (read: “waaay to many”) time learning GraphQL. One of the things I had to figure out was how to call an async method inside a field resolver.
You have 2 options:
- Option 1 - Use the Field<> method and return a Task:
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 interface IProductService | |
{ | |
Task<IList<Product>> GetProducts(); | |
} |
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 IProductService _productService; | |
public ProductssQuery(IProductService productService) | |
{ | |
_productService = productService; | |
Name = "Query"; | |
Field<ListGraphType<ProductType>>( | |
"products", | |
resolve: context => _productService.GetProducts() | |
); | |
} | |
} |
- Option 2 – Use the FieldAsync<> method and await the result:
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 interface IProductService | |
{ | |
Task<IList<Product>> GetProducts(); | |
} |
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 IProductService _productService; | |
public ProductssQuery(IProductService productService) | |
{ | |
_productService = productService; | |
Name = "Query"; | |
FieldAsync<ListGraphType<ProductType>>( | |
"products", | |
resolve: async(context) => await _productService.GetProducts() | |
); | |
} | |
} |