mirror of
https://github.com/zhigang1992/workers-graphql-server.git
synced 2026-05-07 01:41:56 +08:00
Add KV cache support
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
16
src/kv-cache.js
Normal 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
|
||||
Reference in New Issue
Block a user