2.0.1 • Published 3 years ago
apollo-server-integration-cloudflare-workers v2.0.1
apollo-server-integration-cloudflare-workers
⚠️ Warning:
- This package is moved to @as-integrations/cloudlare-workers
- Please migrate to use @as-integrations/cloudlare-workersinstead
This is Apollo Server v4 integration for Cloudflare Workers. It provides:
- kv-cache.ts-- KVCache: Cache on Cloudflare KV storage
- start-server.ts-- startServerAndCreateCloudflareHandler: Handle incoming request and return an instance of- Response
- with-cors-- withCors: Add configure for CORS middleware
Demo
- Source: https://github.com/kimyvgy/worker-apollo-server-template
- Live demo: https://worker-apollo-server.webee-asia.workers.dev/
Install
npm install apollo-server-integration-cloudflare-workersGetting Started
- Initialize an Apollo Server instance:
import { ApolloServer } from '@apollo/server';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
const server = new ApolloServer<ContextValue>({
  typeDefs,
  resolvers,
  introspection: true,
  plugins: [
    ApolloServerPluginLandingPageLocalDefault({ footer: false }),
    // ApolloServerPluginLandingPageProductionDefault({
    //   graphRef: 'my-graph-id@my-graph-variant',
    //   footer: false,
    // })
  ],
});- Call startServerAndCreateCloudflareHandler(server, options):
import type { GraphQLRequestHandler, CorsOptions } from 'apollo-server-integration-cloudflare-workers';
import { startServerAndCreateCloudflareHandler, KVCache } from 'apollo-server-integration-cloudflare-workers';
const handleGraphQLRequest: GraphQLRequestHandler = startServerAndCreateCloudflareHandler(server, {
  context: async ({ request }) => {
    const cache = options.kvCache ? new KVCache() : server.cache;
    const dataSources: ApolloDataSources = {
      pokemonAPI: new PokemonAPI({ cache }),
    };
    return { dataSources };
  },
  // Enable CORS headers on GraphQL requests
  // Set to `true` for defaults or pass an object to configure each header
  // cors: {
  //   allowCredentials: 'true',
  //   allowHeaders: 'Content-type',
  //   allowOrigin: '*',
  //   allowMethods: 'GET, POST, PUT',
  // },
  cors: true,
});
addEventListener((e) => handleGraphQLRequest(e.request));