jeddeloh / rescript-apollo-client

ReScript bindings for the Apollo Client ecosystem
MIT License
127 stars 18 forks source link

How do I use the InMemoryCache's FieldMergeFunction? #143

Closed dfalling closed 2 years ago

dfalling commented 2 years ago

I've dug through the code and haven't found a way to use this merge function. https://github.com/jeddeloh/rescript-apollo-client/blob/7b167c5d0647f1d479246e04c49e39636ae8bfb4/src/%40apollo/client/cache/inmemory/ApolloClient__Cache_InMemory_Policies_FieldPolicy.res#L7-L12

Apollo's documentation suggests the merge field can take either true, to make Apollo handle it, or a function with signature (existing: 't, incoming: 't) => 't. Regardless of what I try to assign to this field, I get an error that it doesn't match the expected type.

jeddeloh commented 2 years ago

So that type t is abstract because the types are unimplemented. You can either cast your field merge function like so:

let myMergeFunction: FieldMergeFunction.Js_.t = Obj.magic((existing, incoming) => { ... })

or you could make a PR to flesh out the types :)

dfalling commented 2 years ago

Perfect- that did the trick! Thank you!

I'd love to PR to help, but the type of this is beyond my understanding... I'm not sure how to have a union type of a function and true that resolve to JS.

module FieldMergeFunction = {
  type t<'existing> =
    | Function(('existing, 'existing) => 'existing)
    | True
}
jeddeloh commented 2 years ago

Great! If you do indeed want to do the work of a PR, I'm happy to help guide you a little, but no pressure.

If you do go down that path, please read the contributing section that explains some of the weird Js_ modules

There's an old blog post about representing unions like this in ReScript: https://rescript-lang.org/blog/union-types-in-bucklescript

And there are many examples in the code. Here is one: https://github.com/jeddeloh/rescript-apollo-client/blob/d75edfd0e4e0a4ac201e2b7424331f6b411b4cd7/src/%40apollo/client/cache/inmemory/ApolloClient__Cache_InMemory_Policies_FieldPolicy.res

dfalling commented 2 years ago

Perfect, thank you! I'll close out this issue and push a WIP PR when I get stumped. Thanks!