Apollo (GraphQL) retrieves more than one item in a query

Is it possible to get more than one element in a GraphQL query? I have a lot of product list data, and I want to get, for example, three products in my component. I have an array of the required product identifiers, can I pass it to the request? This is my request for one product:

query ProductInCartQuery($id: ID!){ Product(id: $id) { id name price } } 

But I don’t think I can just put it in a function and execute it, for example, three times for three products.

+5
source share
2 answers

It is generally accepted and very useful to offer two types of queries for each type that you have:

  • a request to select one node with id or other unique fields that are Product in your case (you already have this).

  • a request to retrieve many nodes depending on different filter conditions, call him allProducts .

Then you have two options for extracting multiple products in one query.

First, you can use the Product query several times and use GraphQL Aliases to avoid name collisions in the response data:

 query ProductInCartQuery($firstId: ID!, $secondId: ID!){ firstProduct: Product(id: $firstId) { id ... ProductInfo } secondProduct: Product(id: $secondId) { id ... ProductInfo } fragment ProductInfo on Product { name price } } 

You can build this query string dynamically depending on the identifiers you want to query. However, it is best to use the allProducts query with the necessary filter setting if the number of differents identifiers is dynamic:

 query filteredProducts($ids: [ID!]!) { allProducts(filter: { id_in: $ids }) { ... ProductInfo } } fragment ProductInfo on Product { name price } 

You can try yourself in this GraphQL playground. I am prepared for you. More information can be found in this article .

+6
source

To add product identifiers to a query, you can define an input type. See cheat sheet .

Thus, a client request may look like this:

 query ProductsInCartQuery($productIds: ProductIds!) { Products(productIds: $productIds) { id name price } } 

On the server, you define a schema with input type as follows:

 input ProductIds { ids: [ID!] } type Query { Products(productIds: ProductIds!) { id name price } } schema { query: Query } 
0
source

Source: https://habr.com/ru/post/1268665/


All Articles