在缓存类型策略中添加嵌套字段 - Apollo v3

Sim*_*aud 8 javascript typescript apollo react-apollo apollo-client

我想知道是否可以使用 InMemoryCache 的 typePolicies 来嵌套值 现在您可以定义平面字段策略

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        hello: {
          read() {
            return 'hello'
          },
        },
        hola: {
          read() {
            return 'hola'
          },
        },
      },
    },
  },
})

// query flat local field using apollo
const QUERY_USER_PAGE = gql`
  query UserPage {
      hello
      hola
  }
`
Run Code Online (Sandbox Code Playgroud)

如果我想要反映我的应用程序结构的 typePolicies 该怎么办,这似乎是一个很好的做法。
扁平结构在大型项目的扩展和维护方面会受到限制。

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        userPage: {
          hello: {
            read() {
              return 'hello'
            },
          },
          hola: {
            read() {
              return 'hola'
            },
          },
        },
      },
    },
  },
})

// query nested local field using apollo:
const QUERY_USER_PAGE = gql`
  query UserPage {
    userPage @client {
      hello
      hola
    }
  }
`
Run Code Online (Sandbox Code Playgroud)

小智 2

您需要添加一个策略UserPage而不是Query

new InMemoryCache({
  typePolicies: {
    UserPage: {
      fields: {
        hello: {
          read() {
            return 'hello'
          },
        },
        hola: {
          read() {
            return 'hola'
          },
        },
      },
    },
  },
})
Run Code Online (Sandbox Code Playgroud)