Skip to content
This repository has been archived by the owner on Feb 9, 2023. It is now read-only.

kimyvgy/apollo-server-integration-cloudflare-workers

Repository files navigation

apollo-server-integration-cloudflare-workers

NPM version

⚠️ Warning:

  • This package is moved to @as-integrations/cloudlare-workers
  • Please migrate to use @as-integrations/cloudlare-workers instead

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

Install

npm install apollo-server-integration-cloudflare-workers

Getting Started

  1. 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,
    // })
  ],
});
  1. 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));

Support / Donate

Support the developer