Add KV cache support

This commit is contained in:
Kristian Freeman
2019-08-21 12:57:17 -07:00
parent 40dcc81d94
commit b838615098
3 changed files with 37 additions and 8 deletions

View File

@@ -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({
const kvCache = { cache: new KVCache() }
const createServer = graphQLOptions =>
new ApolloServer({
typeDefs,
resolvers,
introspection: true,
dataSources,
})
...(graphQLOptions.enableKvCache ? kvCache : {}),
})
const handler = (request, _graphQLOptions) =>
graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request)
const handler = (request, graphQLOptions) => {
const server = createServer(graphQLOptions)
return graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request)
}
module.exports = handler

View File

@@ -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 => {

16
src/kv-cache.js Normal file
View File

@@ -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