Sebbbbbb
Sebbbbbb

Reputation: 131

Apollo Client - Cache Redirects for sub-types

I am using Apollo in production for about a year and I am trying to optimize my cache management. Let's imagine the following fictive simple schema:

type Query {
  allBooks: [Book]
  allCups: [Cup]
  allColors: [Color]
}

type Book {
  id: Int
  name: String
  cover_color_id: Int
  CoverColor: Color
}

type Cup {
  id: Int
  name: String
  cover_color_id: Int
  CoverColor: Color
}

type Color {
  id: Int
  name: String
  hex_code: String
}

I would like to configure cacheRedirects so that when I demand the Book.CoverColor or Cup.CoverColor (via allBooks for instance ); it will first look for the Color with matching ID in the cache, before asking the server for it. Is that possible ?

Thanks in advance!

PS: I tried this, which doesn't seem to work:

cacheRedirects: {
  Query: {
    // Stuff that perfectly works
  },
  Book: {
    // this is not even executed :(
    CoverColor: (book, args, { getCacheKey }) => {
      return getCacheKey({
        __typename: 'Color',
        id: book.cover_color_id
      })
    }
  }
}

Upvotes: 1

Views: 475

Answers (1)

Yevhenii Ponomar
Yevhenii Ponomar

Reputation: 199

It depends on what your queries look like.

if your allBooks redirect returns list of ids and your query has returnPartialData enabled it should work.

if you querying allBooks without hitting redirect, there is no reason for apollo to use cached fields on each element of [Book] if it already has all data

Make a query for a single book and it should work as you expect.

type Query {
  allBooks: [Book]
  allCups: [Cup]
  allColors: [Color]
  book(id: Int): Book
}
const cacheRedirects: CacheResolverMap = {
  Query: {
    book: (_, args, { getCacheKey }) =>
      getCacheKey({ __typename: 'Book', id: `${args.id}` }),
  },
  Book: {
    CoverColor: (book, args, { getCacheKey }) => {
      return getCacheKey({
        __typename: 'Color',
        id: book.cover_color_id,
      })
    },
  },
}

Upvotes: 1

Related Questions