apollo-link-state: How to write Query resolvers?

Viewed 642

I create my state link with defaults values, something like this:

const stateLink = withClientState({
  cache,
  resolvers,
  defaults: {
    quote: {
      __typename: 'Quote',
      name: '',
      phoneNumber: '',
      email: '',
      items: []
    }
  }
})

So my cache should not be empty. Now my resolvers map looks like this:

resolvers = {
  Mutation: { ... },
  Query: {
    quote: (parent, args, { cache }) => {
      const query = gql`query getQuote {
        quote @client {
          name phoneNumber email items
        }
      }`

      const { quote } = cache.readQuery({ query, variables: {} })
      return ({ ...quote })
    }
  }
}

The datasource of my resolvers is the cache right ? so I have to query the cache somehow. But this is not working, I guess it is because I am trying to respond to quote query, and for that I am making another quote query.

I think I should get the quote data without querying for quote, but how ?

I am getting this error:

Can't find field **quote** on object (ROOT_QUERY) undefined

Please help

1 Answers

Just wanted to post the same question - and fortunatly just figured it out. readQuery-Methode only allows you to query from root. So instead you should use readFragment, because it allows you to access any normalized field in the cache, as long you got it's id (Something like this: GraphQlTypeName:0 typically constructed from the fields: id and __typename ). Your Query-Resolver should then look something like this:

  protected resolvers = {
Query: {
  getProdConfig: (parent, args, { cache, getCacheKey }) => {
    const id = getCacheKey({ __typename: 'ProdConfig', id: args.id });
    const fragment = gql`fragment prodConfig on ProdConfig {
      id,
      apiKey,
      backupUrl,
      serverUrl,
      cache,
      valid
    }`;
    const data = cache.readFragment({ fragment, id })
    return ({ ...data });
  }
}

and the call from apollo like:

    let query = this.$apollo.query(`
  query prodConfig($id: Int!) {
    getProdConfig(id: $id) @client {
      apiKey,
      backupUrl,
      serverUrl,
      cache,
      valid
    }
  }`,
  { id: 0 }
);
Related