apollographql / apollo-link-state

✨ Manage your application's state with Apollo!
MIT License
1.4k stars 100 forks source link

Missing example of Query resolver in the doc #296

Closed acmoune closed 6 years ago

acmoune commented 6 years ago

I know my question belongs to stackoverflow, but I am not having a response, so ...

In the doc, there are example of Mutation resolvers, but none of Query resolvers, and I don't know how to make mine to work.

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

acmoune commented 6 years ago

Note that when I remove my query resolvers, things seems to work, but I need to do such queries:

{ 
  quote {
    item(id: "xxxx") { title price quantity }
  }
}

So I need a Query resolver.

acmoune commented 6 years ago

@peggyrayzis Please can you have a look

acmoune commented 6 years ago

I think the problem is that the defaults provided to stateLink constructor don't initial the ROOT_QUERY in the cache.

acmoune commented 6 years ago

I understand now that Query resolvers are only called on cache miss, so I should just return defaults state in my resolver.

In case I provide this initializer resolver, what about the defaults values provided to the stateLink constructor ?

Is it possible to call writeQuery within that resolver ? hoping that writeQuery will update the cache ROOT_QUERY, because writeCache (called for the defaults) is not updating the cache ROOT_QUERY.

acmoune commented 6 years ago

It is like I am crazy talking to myself, I am closing this. If somebody has a look at this one day and want to share something, that will be cool.