简体   繁体   English

无法转换/规范化/修改 GraphQL 查询的响应 - Apollo Client

[英]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.这对 websockets 事件非常有效 - 数据被转换,添加到数据response.data中的这个parsed字段,但在常规<Query...请求中,解析字段被删除,因此组件无法读取它。 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我已经确认在查询请求中正确调用了此方法,并且还添加了parsed字段,但是在 afterware 和组件之间的某个地方, parsed字段被剥离

Apollo Client v3 introduced a feature for customizing the behavior of cached fields : Apollo Client v3 引入了一个用于自定义缓存字段行为的功能:

You can customize how individual fields in the Apollo Client cache are read and written.您可以自定义 Apollo 客户端缓存中各个字段的读取和写入方式。 To do so, you define a FieldPolicy object for a given field.为此,您FieldPolicy为给定字段定义一个FieldPolicy对象。 You nest a FieldPolicy object within whatever TypePolicy object corresponds to the type that contains the field.您可以在与包含该字段的类型对应的任何TypePolicy对象中嵌套一个FieldPolicy对象。

Here's how to parse date strings into Date objects:以下是将日期字符串解析为 Date 对象的方法:

export const apolloClient = new ApolloClient({
  link: ...,
  cache: new InMemoryCache({
    typePolicies: {
      Post: {
        fields: {
          updatedAt: {
            read(time: string) {
              return new Date(time);
            },
          },
        },
      },
    },
  }),
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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