Skip to content

Commit 106fa88

Browse files
Merge pull request #58 from cloudflare/update
v2
2 parents 7a5e8c5 + 583ebb7 commit 106fa88

27 files changed

+12099
-2557
lines changed

.editorconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[*]
2+
indent_style = space
3+
indent_size = 2

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,5 @@ $RECYCLE.BIN/
215215

216216
### Cloudflare ###
217217
worker
218+
219+
src/generated

LICENSE

Lines changed: 0 additions & 21 deletions
This file was deleted.

README.md

Lines changed: 75 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,66 @@
11
# workers-graphql-server
22

3-
An [Apollo GraphQL](https://www.apollographql.com/) server, built with [Cloudflare Workers](https://workers.cloudflare.com). [Try a demo by looking at a deployed GraphQL playground](https://graphql-on-workers.signalnerve.com/___graphql).
3+
An [Apollo GraphQL](https://www.apollographql.com/) server, built with [Cloudflare Workers](https://workers.cloudflare.com).
44

5-
Why this rules: Cloudflare Workers is a serverless application platform for deploying your projects across Cloudflare's massive distributed network. Deploying your GraphQL application to the edge is a huge opportunity to build consistent low-latency API servers, with the added benefits of "serverless" (I know, the project has `server` in it): usage-based pricing, no cold starts, and instant, easy-to-use deployment software, using [Wrangler](https://github.com/cloudflare/wrangler).
5+
Whether you host your APIs on-prem, in the cloud, or you're deploying [databases](https://developers.cloudflare.com/d1) to Cloudflare directly, you can deploy a globally distributed GraphQL server with Cloudflare Workers.
66

7-
By the way - as a full-stack developer who _loves_ GraphQL, and the developer advocate for Cloudflare Workers, I would love to see what you build with this! Let me know [on Twitter](https://twitter.com/signalnerve)!
7+
## Setup
88

9-
[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/workers-graphql-server)
10-
11-
## Usage
12-
13-
You can begin building your own Workers GraphQL server by [installing Wrangler](https://workers.cloudflare.com/docs/quickstart/), the Workers command-line tool, and generating a new project:
9+
Begin by cloning this repo and installing the dependencies:
1410

1511
```sh
16-
wrangler generate my-graphql-server https://github.com/cloudflare/workers-graphql-server
12+
$ git clone https://github.com/cloudflare/workers-graphql-server
13+
$ npm install
1714
```
1815

19-
You'll need to configure your project's `wrangler.toml` file to prepare your project for deployment. See the ["Configuration"](https://developers.cloudflare.com/workers/cli-wrangler/configuration/) docs for a guide on how to do this. Note that you'll need to [find your Cloudflare API keys](https://developers.cloudflare.com/workers/cli-wrangler/authentication/) to set up your config file.
16+
You can begin running the project locally by running `npm run dev`.
17+
18+
You'll need to configure your project's `wrangler.toml` file to prepare your project for deployment. See the ["Configuration"](https://developers.cloudflare.com/workers/cli-wrangler/configuration/) docs for a guide on how to do this.
19+
20+
## Usage
2021

21-
The source for this project includes an example external REST data source, and defined types for the [PokeAPI](https://pokeapi.co/), as an example of how to integrate external APIs. Once you have the worker available, try this query as a sanity check:
22+
The source for this project shows how to make requests to external APIs, using the [PokeAPI](https://pokeapi.co/) as an example. You can run an example query to ensure it works after deployment:
2223

2324
```graphql
24-
query samplePokeAPIquery {
25-
pokemon: pokemon(id:1) {
26-
id,
27-
name,
28-
height,
29-
weight,
30-
sprites{
31-
front_shiny,
25+
query {
26+
pokemon: pokemon(id: 1) {
27+
id
28+
name
29+
height
30+
weight
31+
sprites {
32+
front_shiny
3233
back_shiny
3334
}
3435
}
3536
}
3637
```
3738

38-
To start using the project, configure your `graphQLOptions` object in `src/index.js`:
39+
Resolvers are defined in `src/resolvers.ts`. You can also use [Service Bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to connect to other Workers services, and use them inside your resolvers.
40+
41+
If you change your GraphQL schema at `src/schema.graphql`, you'll need to run `npm run codegen` to update the generated types in `src/generated/graphql.ts`. This ensures that you can correctly import and type your resolvers.
42+
43+
## Configuration
44+
45+
You can optionally configure your `graphQLOptions` object in `src/index.js`:
3946

4047
```js
4148
const graphQLOptions = {
42-
baseEndpoint: '/', // String
43-
playgroundEndpoint: '/___graphql', // ?String
44-
forwardUnmatchedRequestsToOrigin: false, // Boolean
45-
debug: false, // Boolean
46-
cors: true, // Boolean or Object to further configure
47-
kvCache: false, // Boolean
49+
baseEndpoint: '/',
50+
enableSandbox: true,
51+
forwardUnmatchedRequestsToOrigin: false,
52+
cors: true,
53+
kvCache: false,
4854
}
4955
```
5056

51-
### Endpoints
57+
### Base endpoint
58+
59+
Make requests to your GraphQL server by sending `POST` requests to the `baseEndpoint` (e.g. `graphql-on-workers.signalnerve.com/`).
60+
61+
### Sandbox
5262

53-
Make requests to your GraphQL server at the `baseEndpoint` (e.g. `graphql-on-workers.signalnerve.com/`) and, if configured, try GraphQL queries at the `playgroundEndpoint` (e.g. `graphql-on-workers.signalnerve.com/___graphql`).
63+
By default, the Apollo Sandbox is enabled. This allows you to test your GraphQL in a web GUI without needing to write any client code.
5464

5565
### Origin forwarding
5666

@@ -62,37 +72,64 @@ While configuring your server, you may want to set the `debug` flag to `true`, t
6272

6373
### CORS
6474

65-
By default, the `cors` option allows cross-origin requests to the server from any origin. You may wish to configure it to whitelist specific origins, methods, or headers. To do this, change the `cors` option to an object:
75+
By default, the `cors` option allows cross-origin requests to the server from any origin. You may wish to configure it to whitelist specific origins, methods, or headers. This is done by passing an object to `cors`, which is based on the [hono/cors](https://hono.dev/docs/middleware/builtin/cors) middleware:
6676

6777
```js
6878
const graphQLOptions = {
6979
// ... other options ...
7080

7181
cors: {
72-
allowCredentials: 'true',
73-
allowHeaders: 'Content-type',
74-
allowOrigin: '*',
75-
allowMethods: 'GET, POST, PUT',
82+
origin: 'http://example.com',
83+
allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
84+
allowMethods: ['POST', 'GET', 'OPTIONS'],
85+
exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
86+
maxAge: 600,
87+
credentials: true,
7688
},
7789
}
7890
```
7991

80-
Note that by default, any field that you _don't_ pass here (e.g. `allowMethods`) will fallback to the default value. See `utils/setCors.js` for the default values for these fields.
92+
### Caching
8193

82-
### REST caching
83-
84-
Version 1.1.0 of this project includes support for caching external requests made via instances of [`RESTDataSource`](https://www.apollographql.com/docs/apollo-server/features/data-sources/), using KV. To use caching in your project, [create a new KV namespace](https://workers.cloudflare.com/docs/reference/storage/writing-data), and in `wrangler.toml`, configure your namespace, calling it `WORKERS_GRAPHQL_CACHE`:
94+
This project includes support for using Workers KV as a cache in your resolvers. To use caching in your project, [create a new KV namespace](https://workers.cloudflare.com/docs/reference/storage/writing-data), and in `wrangler.toml`, configure your namespace, calling it `KV_CACHE` (note that this binding name is _required_, currently):
8595

8696
```toml
8797
# wrangler.toml
8898

8999
[[kv-namespaces]]
90-
binding = "WORKERS_GRAPHQL_CACHE"
100+
binding = "KV_CACHE"
91101
id = "$myId"
92102
```
93103

94104
With a configured KV namespace set up, you can opt-in to KV caching by changing the `kvCache` config value in `graphQLOptions` (in `index.js`) to `true`.
95105

106+
In any resolver function, you can access the `cache` object, which is an instance of [`KVCache`](https://github.com/cloudflare/workers-graphql-server/blob/master/src/kv-cache.ts). You can use `.get` and `.set` to interact with the cache:
107+
108+
```ts
109+
pokemon: async (_parent, { id }, { cache }) => {
110+
if (cache) {
111+
const pokemon = await cache.get(id)
112+
if (pokemon) {
113+
return pokemon
114+
}
115+
}
116+
117+
// You can hook into any util functions, API wrappers, or other
118+
// code that you need to resolve your query.
119+
const pokemonData = await PokemonAPI.getPokemon(id)
120+
121+
// You can also cache the data if you need to, with an optional TTL
122+
if (cache) await cache.set(id, pokemonData, { ttl: 60 })
123+
return pokemonData
124+
},
125+
```
126+
127+
## Credits
128+
129+
This project is heavily based on the [@as-integrations/cloudflare-workers](https://github.com/apollo-server-integrations/apollo-server-integration-cloudflare-workers) package, which is a great tool for building GraphQL servers with Cloudflare Workers.
130+
131+
It is built with [Hono](https://github.com/honojs/hono), a simple and powerful web framework for Cloudflare Workers.
132+
96133
## License
97134

98135
This project is licensed with the [MIT License](https://github.com/cloudflare/workers-graphql-server/blob/master/LICENSE).

cargo-generate.toml

Lines changed: 0 additions & 2 deletions
This file was deleted.

codegen.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import type { CodegenConfig } from '@graphql-codegen/cli'
2+
3+
const config: CodegenConfig = {
4+
overwrite: true,
5+
schema: 'src/schema.graphql',
6+
generates: {
7+
'src/generated/graphql.ts': {
8+
plugins: ['typescript', 'typescript-resolvers'],
9+
},
10+
'./graphql.schema.json': {
11+
plugins: ['introspection'],
12+
},
13+
},
14+
}
15+
16+
export default config

0 commit comments

Comments
 (0)