mercurius-js / cache

Adds an in-process caching layer to Mercurius. Federation is fully supported.
MIT License
106 stars 19 forks source link

enable cache on federated service #71

Closed simone-sanfratello closed 2 years ago

simone-sanfratello commented 2 years ago

at the moment, we can only cache queries defined in Query gql schema; in a federated service, we may have the follow scenario

const fastify = require('fastify')
const mercurius = require('mercurius')
const cache = require('mercurius-cache')

const app = fastify({ logger: true })

const schema = `
type User @key(fields: "id") {
  id: ID!
  name: String
}
`

const resolvers = {
  Query: {},

  User: {
    __resolveReference: async (source, args, context, info) => {
      return { id: source.id, name: `user #${source.id}` }
    }
  }

}

app.register(mercurius, {
  schema,
  resolvers,
  federationMetadata: true,
})

app.register(cache, {
  ttl: 10,
  policy: {
    Query: {},
    User: true
  }
})

app.listen(3000)

const query = `query ($representations: [_Any!]!) {
  _entities(representations: $representations) {
    ... on User { id, name }
  }
}`

const variables = {
  representations: [
    {
      __typename: 'User',
      id: 123,
    },
  ],
}

// run the following to test

console.log(`curl -X POST -H 'content-type: application/json' `
`-d '`+JSON.stringify({query, variables}) + `' `+
`localhost:3000/graphql`)

and we want to cache User entities

Also note, we need policy: { Query: {} in options, or we get an obscure error

UnhandledPromiseRejectionWarning: TypeError: Cannot convert undefined or null to object

mcollina commented 2 years ago

Also note, we need policy: { Query: {} in options, or we get an obscure error

This is fixed in #75