简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM