apollographql / apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
Other
130 stars 7 forks source link

Allow to provide custom OptimisticCacheLayer #100

Open stalniy opened 5 years ago

stalniy commented 5 years ago

Purpose

I want to implement custom Apollo Cache on top of existing InMemoryCache. The only thing which I want to change is underlying DataStore class, so instead of using ObjectCache or DepTrackingCache I want to use my custom implementation based on Vue reactivity system. So, that all changes to cache becomes immediately visible in my Vue components.

Actual issue

All works good, except of optimisticResponse. This is due to the fact that OptimisticCacheLayer inherits ObjectCache (https://github.com/apollographql/apollo-client/blob/master/packages/apollo-cache-inmemory/src/inMemoryCache.ts#L54) and later usage of OptimisticCacheLayer is hardcoded inside InMemoryCache in 2 places (https://github.com/apollographql/apollo-client/blob/master/packages/apollo-cache-inmemory/src/inMemoryCache.ts#L247, https://github.com/apollographql/apollo-client/blob/master/packages/apollo-cache-inmemory/src/inMemoryCache.ts#L284). So, there is no easy way to substitute implementation of OptimisticCacheLayer and I need to copy/paste 2 methods removeOptimistic and performTransaction from InMemoryCache into my implementation just because I want to add reactivity into OptimisticCacheLayer class.

Solution

If OptimisticCacheLayer class would be stored as a property of InMemoryCache I'd be able to overwrite it in constructor without copying methods (and later synchronizing them with new versions of InMemoryCache). Something like this:

export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
    private OptimisticCacheLayer = OptimisticCacheLayer;
}

And later use this.OptimisticCacheLayer instead of OptimisticCacheLayer

stalniy commented 5 years ago

By the way, I can create a PR if you are ok with the direction