diff --git a/src/handlers/apollo.js b/src/handlers/apollo.js index 1bad6f9..fcde85e 100644 --- a/src/handlers/apollo.js +++ b/src/handlers/apollo.js @@ -1,6 +1,7 @@ const { ApolloServer } = require('apollo-server-cloudflare') const { graphqlCloudflare } = require('apollo-server-cloudflare/dist/cloudflareApollo') +const KVCache = require('../kv-cache') const PokemonAPI = require('../datasources/pokeapi') const resolvers = require('../resolvers') const typeDefs = require('../schema') @@ -9,14 +10,20 @@ const dataSources = () => ({ pokemonAPI: new PokemonAPI(), }) -const server = new ApolloServer({ - typeDefs, - resolvers, - introspection: true, - dataSources, -}) +const kvCache = { cache: new KVCache() } -const handler = (request, _graphQLOptions) => - graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request) +const createServer = graphQLOptions => + new ApolloServer({ + typeDefs, + resolvers, + introspection: true, + dataSources, + ...(graphQLOptions.enableKvCache ? kvCache : {}), + }) + +const handler = (request, graphQLOptions) => { + const server = createServer(graphQLOptions) + return graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request) +} module.exports = handler diff --git a/src/index.js b/src/index.js index 8f662cd..ac4277f 100644 --- a/src/index.js +++ b/src/index.js @@ -26,6 +26,12 @@ const graphQLOptions = { // allowOrigin: '*', // allowMethods: 'GET, POST, PUT', // }, + + // Enable KV caching for external REST data source requests + // Note that you'll need to add a KV namespace called + // WORKERS_GRAPHQL_CACHE in your wrangler.toml file for this to + // work! See the project README for more information. + enableKvCache: false } const handleRequest = request => { diff --git a/src/kv-cache.js b/src/kv-cache.js new file mode 100644 index 0000000..d74f6b9 --- /dev/null +++ b/src/kv-cache.js @@ -0,0 +1,16 @@ +class KVCache { + get(key) { + return WORKERS_GRAPHQL_CACHE.get(key) + } + + set(key, value, options) { + const opts = {} + const ttl = options && options.ttl + if (ttl) { + opts.expirationTtl = ttl + } + return WORKERS_GRAPHQL_CACHE.put(key, value, opts) + } +} + +module.exports = KVCache