Skip to content

Commit 5d6a28b

Browse files
Merge pull request #13 from signalnerve/kristian/kv-caching
Add KV cache support
2 parents a36c488 + b838615 commit 5d6a28b

File tree

3 files changed

+37
-8
lines changed

3 files changed

+37
-8
lines changed

src/handlers/apollo.js

+15-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const { ApolloServer } = require('apollo-server-cloudflare')
22
const { graphqlCloudflare } = require('apollo-server-cloudflare/dist/cloudflareApollo')
33

4+
const KVCache = require('../kv-cache')
45
const PokemonAPI = require('../datasources/pokeapi')
56
const resolvers = require('../resolvers')
67
const typeDefs = require('../schema')
@@ -9,14 +10,20 @@ const dataSources = () => ({
910
pokemonAPI: new PokemonAPI(),
1011
})
1112

12-
const server = new ApolloServer({
13-
typeDefs,
14-
resolvers,
15-
introspection: true,
16-
dataSources,
17-
})
13+
const kvCache = { cache: new KVCache() }
14+
15+
const createServer = graphQLOptions =>
16+
new ApolloServer({
17+
typeDefs,
18+
resolvers,
19+
introspection: true,
20+
dataSources,
21+
...(graphQLOptions.enableKvCache ? kvCache : {}),
22+
})
1823

19-
const handler = (request, _graphQLOptions) =>
20-
graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request)
24+
const handler = (request, graphQLOptions) => {
25+
const server = createServer(graphQLOptions)
26+
return graphqlCloudflare(() => server.createGraphQLServerOptions(request))(request)
27+
}
2128

2229
module.exports = handler

src/index.js

+6
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ const graphQLOptions = {
2626
// allowOrigin: '*',
2727
// allowMethods: 'GET, POST, PUT',
2828
// },
29+
30+
// Enable KV caching for external REST data source requests
31+
// Note that you'll need to add a KV namespace called
32+
// WORKERS_GRAPHQL_CACHE in your wrangler.toml file for this to
33+
// work! See the project README for more information.
34+
enableKvCache: false
2935
}
3036

3137
const handleRequest = async request => {

src/kv-cache.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class KVCache {
2+
get(key) {
3+
return WORKERS_GRAPHQL_CACHE.get(key)
4+
}
5+
6+
set(key, value, options) {
7+
const opts = {}
8+
const ttl = options && options.ttl
9+
if (ttl) {
10+
opts.expirationTtl = ttl
11+
}
12+
return WORKERS_GRAPHQL_CACHE.put(key, value, opts)
13+
}
14+
}
15+
16+
module.exports = KVCache

0 commit comments

Comments
 (0)