Add nested fields in cache typePolicies - Apollo v3

Viewed 481

I am wondering if it is possible to have nested values using typePolicies of the InMemoryCache For now you can define flat fields policies

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
  }
`

What if I want to have typePolicies that reflect the structure of my App which seems to be a good practice.
Flat structure will have limitations concerning scaling and maintenance for large project..

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
    }
  }
`
1 Answers

You need to add a policy in UserPage instead of Query

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