apollographql / apollo-cache-control

A GraphQL extension for cache control
146 stars 6 forks source link

working example of cache control? #5

Open Jinnified opened 6 years ago

Jinnified commented 6 years ago

Hi

I am trying to implement cacheControl following this guide: https://www.apollographql.com/docs/engine/caching.html

I have one single huge REST api which spits out about 1000 fields for each request. and i have added a layer of graphql in my Express server on top of this REST endpoint, with a resolver return a promise.

I have broken down all the fields into about 40 schema files, and on each schema i have added a cachecontrol annotation, like so:

type Agent @cacheControl(maxAge: 240) {
  id: Int!
  name: String
  type: String
}

and I am using apollo-server-express and apollo-engine for the graphql server setup, like so:

import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';
import { ApolloEngine } from 'apollo-engine';

const engine = new ApolloEngine({
  apiKey: constants.APOLLO_ENGINE_API_KEY,
  origins: [{
    supportsBatch: true,
    requestTimeout: '60s',
  }],

  // Resize the default in-memory cache.
  stores: [{
    name: 'inMemEmbeddedCache',
    inMemory: {
      cacheSize: 104857600,  // 100 MB; defaults to 50MB.
    },
  }],
  queryCache: {
    publicFullQueryStore: 'inMemEmbeddedCache',
  },
});

app.use(
    '/graphql',
    bodyParser.json(),
    graphqlExpress({
      schema,
      tracing: true, // for apollo engine tracing and reporting to work
      cacheControl: true, // for apollo engine caching mechanism
    }),
  );

versions: apollo-server-express: 1.3.4 apollo-engine: 1.0.4 express:4.15.2

then when i tested it, i expect my resolver (which will make the HTTP call to that huge REST endpoint) should only gets run ONCE every 240 seconds, but what actually happened is that resolver gets called every time a graphql query gets run regardless, doesn't look like the cache is working, or did i miss anything?

martijnwalraven commented 6 years ago

It seems you may be missing:

engine.listen({
  port: 3000,
  expressApp: app,
});

See https://www.apollographql.com/docs/engine/setup-node.html#apollo-engine

pabl-o-ce commented 6 years ago

Hi @martijnwalraven what about a example using apolloServer 2.0. Im trying but when a consume you have to specify in the client the header of cache control (is mandatory that?).