apollo-client icon indicating copy to clipboard operation
apollo-client copied to clipboard

Type-level merge function not called for nested array items

Open Huulivoide opened this issue 2 years ago • 6 comments

Intended outcome:

When defining a Type-level merge function:

new InMemoryCache({
  typePolicies: { LevelB: { merge: mergeB } }
});

I expect mergeB function to get called any time a LevelB item is written to the cache normally.

Actual outcome:

Currently mergeB is only called if LevelB item is returned as a single value, but not when it is returned inside of an array.

query { querySingle: { singleB: { id } } }

Does work and calls the mergeB merge function, but:

query { queryAll: { allBs: { id } } }

does not call the merge function for the LevelB items.

How to reproduce the issue: Reproduction at: https://github.com/Huulivoide/apollo-nested-merge When run, one expects to see the merge function to be run for all Item levels, but merging is omitted for levels/items that are returned in arrays (Items B and D).

Versions System: OS: Linux 5.18 Arch Linux Binaries: Node: 18.3.0 - /usr/bin/node Yarn: 1.22.19 - /usr/bin/yarn npm: 8.5.5 - /usr/bin/npm Browsers: Chrome: 102.0.5005.115 Firefox: 101.0.1 npmPackages: @apollo/client: ^3.6.8 => 3.6.8 npmGlobalPackages: apollo: 2.33.3

Huulivoide avatar Jun 15 '22 13:06 Huulivoide

I belive the problem lies around here https://github.com/apollographql/apollo-client/blob/67a13b5331047264797cb50e2b19bf1ae6bacd85/src/cache/inmemory/writeToStore.ts#L321

StoreWriter.processSelectionSet().flattenFields

If the value is an array it is treated like a scalar, instead of being recursed into.

Huulivoide avatar Jun 16 '22 10:06 Huulivoide

Is the entity returned from the querySingle be also present in the array of entities of allBs? If no - merge function should not get called I believe

bohdanbirdie avatar Jun 17 '22 18:06 bohdanbirdie

@Huulivoide Thank you for reporting this! You seemed to track this issue down to the line of code mentioned above, I was curious if you had the time to make a PR we could consider to fix this?

jpvajda avatar Jun 17 '22 23:06 jpvajda

I am also experiencing this problem

alan-bradbury avatar Aug 10 '23 20:08 alan-bradbury

Oh my, I had completely forgotten about this after implementing workarounds. I'll have to try and remember to get back at this after my long awaited summer vacation in a month or so.

Huulivoide avatar Aug 10 '23 22:08 Huulivoide

What workarounds did you implement? @Huulivoide

simPod avatar Jan 15 '24 18:01 simPod