Cloudflare Workers Integration with Worktop#
This integration is based on the framework Worktop
Install#
yarn add worktop graphql graphql-ez @graphql-ez/cloudflare
yarn add -D @types/nodepnpm add worktop graphql graphql-ez @graphql-ez/cloudflare
pnpm add -D @types/nodenpm install worktop graphql graphql-ez @graphql-ez/cloudflare
npm install -D @types/nodeDevelopment#
We recommended to use Miniflare, esbuild and concurrently for development.
yarn add -D miniflare esbuild concurrentlypnpm add -D miniflare esbuild concurrentlynpm install -D miniflare esbuild concurrentlyAnd a common development scripts set should look something like this:
{
  "scripts": {
    "build": "esbuild src/index.ts --target=es2020 --minify --bundle --outfile=dist/worker.js",
    "dev": "concurrently -r \"esbuild src/index.ts --target=es2020 --minify --bundle --outfile=dist/worker.js --watch\" \"miniflare dist/worker.js --watch\"",
    "start": "miniflare dist/worker.js"
  }
}
Usage#
Server module
import { listen } from 'worktop/cache';
import { ezApp } from './ez';
const { router } = ezApp.buildApp();
router.add('GET', '/', (_req, res) => {
  res.send(200, { hello: 'Hello World!' });
});
listen(router.run);
EZ App module
import { CreateApp } from '@graphql-ez/cloudflare';
export const ezApp = CreateApp({
  // You can use any valid GraphQL Schema
  schema,
  ez: {
    plugins: [
      // EZ Plugins
    ],
  },
  envelop: {
    plugins: [
      // Envelop Plugins
    ],
  },
  // Other Options
});
Build Custom Context#
import { CreateApp, BuildContextArgs, InferContext } from '@graphql-ez/cloudflare';
function buildContext({ req, cloudflare }: BuildContextArgs) {
  // IncomingMessage-like
  req;
  // ServerRequest
  cloudflare!.req;
  return {
    foo: 'bar',
  };
}
// This snippet allows you to infer the context returned by your 'buildContext' and add it to the EZContext interface
declare module 'graphql-ez' {
  interface EZContext extends InferContext<typeof buildContext> {}
}
export const ezApp = CreateApp({
  // ...
  buildContext,
});
Cross-Origin Resource Sharing (CORS)#
To enable CORS, specify the cors property in your configuration
CreateApp({
  cors: true,
});
Check worktop/cors types for all the available options.
CreateApp({
  // Check https://github.com/lukeed/worktop/blob/master/src/cors.d.ts
  cors: {
    // ...
  },
});