Hello everyone! I have a rather obvious problem that I can’t seem to solve.
Let’s say I have a Category
type and a Product
type. A category can have multiple products, but a product can only have one category. Let’s say the schema is
type Category {
id: ID!
products: [Product!]!
}
type Product {
id: ID!
name: String!
category: Category!
}
type Query {
category(id: ID!): Category
product(id: ID!): Product
}
As you can see, type Product has one category linked to it. Also, I can query a category by ID or a product by ID.
Now let’s say I make a query
query {
category(id: 1) {
id
products {
id
name
}
}
}
Basically here I’m querying a specific category and all products within it.
Let’s say as a result I got a single product with ID 2:
{
"category": {
"id": 1,
"products": [ { "id": 2, "name": "My product" } ]
}
}
Apollo will save the result into the cache. After that I make this 2nd query:
query {
product(id: 2) {
id
name
category {
id
}
}
}
I know that the category of this product has ID = 1, because in the previous query, the product with ID = 2 was inside the category with ID = 1. But unfortunately Apollo Client does not know that, so the 2nd query will be a cache miss.
How do I solve this? How do I “link” every product within a category to that category, so Apollo “understands” that if products X and Y are in the products array of the category A, then category A is in the category field of the product X?
Thank you!