#graphql #apollo #apollo-client
Вопрос:
В своем приложении я ищу продукты, а затем нажимаю на продукт, чтобы узнать о нем более подробную информацию.
Я выполняю запрос GraphQL на каждой странице. SEARCH
Запрос возвращает тип [Продукт], а PRODUCT
запрос возвращает тип продукта.
// Search page
const SEARCH = gql`
query Search($query: String!) {
searchResults: search(query: $query) {
id
name
images
price
}
}
`
// ProductDetail page
const PRODUCT = gql`
query Product($id: Int!, $isShallow: Boolean) {
product(id: $id, isShallow: $isShallow) {
id
name
images
optionSetName
options {
id
images
name
}
price
}
}
`
Я определил функцию слияния product
, потому что я хочу объединить данные из SEARCH
в данные из PRODUCT
(это странная реализация, но в основном она позволяет мне пропустить запрос SQL, указав isShallow
arg):
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
product: {
merge (_, incoming, { args, toReference, readField }) {
const existingProduct = toReference({
__typename: 'Product',
id: args.id
})
console.log(`existingProduct: ${existingProduct}`)
console.log(`incoming: ${incoming}`)
console.log(`readField('name', existingProduct): ${readField('name', existingProduct)}`)
console.log(`readField('name', incoming): ${readField('name', incoming)}`)
return { ...incoming, ...existingProduct }
}
}
}
}
}
})
Вот кэш после выполнения SEARCH
запроса, но перед выполнением PRODUCT
запроса:
{
"ROOT_QUERY":{
"search({"query":"shower"})":[
{
"__ref":"Product:2"
},
{
"__ref":"Product:1"
}
]
},
"Product:2":{
"id":2,
"__typename":"Product",
"name":"Conditioner",
"images":[
"magpie.png"
],
"price":"10.50"
},
"Product:1":{
"id":1,
"__typename":"Product",
"name":"Shampoo",
"images":[
"fancy.png",
"soap.png",
"bee.png"
],
"price":"20.00"
}
}
When I click into the ProductDetail page and execute the PRODUCT
query, I get the following output in console (from merge
):
existingProduct: {__ref: 'Product:2'}
incoming: {__ref: 'Product:2'}
readField('name', existingProduct): null
readField('name', incoming): null
It seems like Product:2.name
, which was Conditioner
before executing the PRODUCT
query, has already been saved to the cache as null
while still in the merge function. How can I access it as Conditioner
so I can merge it as I wish?
Using "@apollo/client": "^3.4.1"