Rafael Sales
Rafael Sales

Reputation: 336

Can't transform/normalize/modify response of GraphQL query - Apollo Client

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

Upvotes: 2

Views: 3040

Answers (1)

Dan Dascalescu
Dan Dascalescu

Reputation: 151988

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);
            },
          },
        },
      },
    },
  }),
});

Upvotes: 3

Related Questions