0.3.0 • Published 23 hours ago

@envelop/response-cache-cloudflare-kv v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
23 hours ago

@envelop/response-cache-cloudflare-kv

Check out the GraphQL Response Cache Guide for more information

Getting Started

yarn add @envelop/response-cache
yarn add @envelop/response-cache-cloudflare-kv

Usage Example

In order to use the Cloudflare KV cache, you need to:

  • Create a Cloudflare KV namespace
  • Add that namespace to your wrangler.toml in order to access it from your worker. Read the KV docs to get started.
  • Pass the KV namespace to the createKvCache function and set to the useResponseCache plugin options. See the example below.
import { createSchema, createYoga, YogaInitialContext } from 'graphql-yoga'
import { useResponseCache } from '@envelop/response-cache'
import { createKvCache } from '@envelop/response-cache-cloudflare-kv'
import { resolvers } from './graphql-schema/resolvers.generated'
import { typeDefs } from './graphql-schema/typeDefs.generated'

export type Env = {
  GRAPHQL_RESPONSE_CACHE: KVNamespace
}
export type GraphQLContext = YogaInitialContext & Env & ExecutionContext

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const kvCache = createKvCache({
      KV: env.GRAPHQL_RESPONSE_CACHE,
      ctx,
      keyPrefix: 'graphql' // optional
    })

    const graphqlServer = createYoga<GraphQLContext>({
      schema: createSchema({ typeDefs, resolvers }),
      plugins: [
        useResponseCache({
          cache: kvCache,
          session: () => null,
          includeExtensionMetadata: true,
          ttl: 1000 * 10 // 10 seconds
        })
      ]
    })

    return graphqlServer.fetch(request, env, ctx)
  }
}
0.3.0

5 months ago

0.2.0

6 months ago