2

Anyone had experience with an afterware that modifies the response data?

  const parseResponse = new ApolloLink((operation, forward) => {
    return forward(operation).map((response) => {
      response.data.parsed = transformData(response.data)
      return response
    })
  })
  const link = parseResponse.concat(networkLink)

This works great on websockets events - the data is transformed, added to this parsed field in the data response.data, but on a regular <Query... request, the parsed field is deleted so the component can't read it. I've confirmed that this method is called correctly in query requests and that the parsed field is added as well, but somewhere between the afterware and the component the parsed field gets stripped

Rafael Sales
  • 326
  • 5
  • 8
  • Queries actually act like a _redux-selector_ and only get the fields they are querying for. This means that your queries actually run on the cache. When a query result comes in it is integrated into the cache and then from there gets into your component. I think this is where the field gets lost. What you are doing here looks like it will get you into trouble at some point. Consider solving this problem differently, e.g. parsing in the component. – Herku Jul 20 '18 at 12:29
  • 1
    Always parsing in the component means unnecessary boilerplate. With REST API, I just create a middleware that normalizes the message. Ideally, ApolloClient should provide a middleware mechanism where I could transform the response between the cache and the client :/ – Rafael Sales Jul 20 '18 at 15:28

1 Answers1

3

Apollo Client v3 introduced a feature for customizing the behavior of cached fields:

You can customize how individual fields in the Apollo Client cache are read and written. To do so, you define a FieldPolicy object for a given field. You nest a FieldPolicy object within whatever TypePolicy object corresponds to the type that contains the field.

Here's how to parse date strings into Date objects:

export const apolloClient = new ApolloClient({
  link: ...,
  cache: new InMemoryCache({
    typePolicies: {
      Post: {
        fields: {
          updatedAt: {
            read(time: string) {
              return new Date(time);
            },
          },
        },
      },
    },
  }),
});
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404