Giter VIP home page Giter VIP logo

workers-graphql-server's Introduction

workers-graphql-server

An Apollo GraphQL server, built with Cloudflare Workers. Try a demo by looking at a deployed GraphQL playground.

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.

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!

Deploy to Cloudflare Workers

Usage

You can begin building your own Workers GraphQL server by installing Wrangler, the Workers command-line tool, and generating a new project:

wrangler generate my-graphql-server https://github.com/cloudflare/workers-graphql-server

You'll need to configure your project's wrangler.toml file to prepare your project for deployment. See the "Configuration" docs for a guide on how to do this. Note that you'll need to find your Cloudflare API keys to set up your config file.

The source for this project includes an example external REST data source, and defined types for the PokeAPI, as an example of how to integrate external APIs. Once you have the worker available, try this query as a sanity check:

query samplePokeAPIquery {
  pokemon: pokemon(id:1) {
    id,
    name,
    height,
    weight,
    sprites{
      front_shiny,
      back_shiny
    }
  }
}

To start using the project, configure your graphQLOptions object in src/index.js:

const graphQLOptions = {
  baseEndpoint: '/', // String
  playgroundEndpoint: '/___graphql', // ?String
  forwardUnmatchedRequestsToOrigin: false, // Boolean
  debug: false, // Boolean
  cors: true, // Boolean or Object to further configure
  kvCache: false, // Boolean
}

Endpoints

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).

Origin forwarding

If you run your GraphQL server on a domain already registered with Cloudflare, you may want to pass any unmatched requests from inside your Workers script to your origin: in that case, set forwardUnmatchedRequestToOrigin to true (if you're running a GraphQL server on a Workers.dev subdomain, the default of false is fine).

Debugging

While configuring your server, you may want to set the debug flag to true, to return script errors in your browser. This can be useful for debugging any errors while setting up your GraphQL server, but should be disabled on a production server.

CORS

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:

const graphQLOptions = {
  // ... other options ...

  cors: {
    allowCredentials: 'true',
    allowHeaders: 'Content-type',
    allowOrigin: '*',
    allowMethods: 'GET, POST, PUT',
  },
}

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.

REST caching

Version 1.1.0 of this project includes support for caching external requests made via instances of RESTDataSource, using KV. To use caching in your project, create a new KV namespace, and in wrangler.toml, configure your namespace, calling it WORKERS_GRAPHQL_CACHE:

# wrangler.toml

[[kv-namespaces]]
binding = "WORKERS_GRAPHQL_CACHE"
id = "$myId"

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.

License

This project is licensed with the MIT License.

workers-graphql-server's People

Contributors

abernix avatar kristianfreeman avatar timecode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

workers-graphql-server's Issues

Migrate to Wrangler 2

With the release of Wrangler 2, there are a variety of deprecations that should be handled in the wrangler.toml file, as well as a build process change for webpack based workers. Most importantly, Wrangler 2 now supports the ESM module syntax, which will require a number of source code changes.

We're going to try getting a PR for this together in the upgrade of our own project, but wanted to track this ticket.

Example Apollo Federation with Apollo Gateway

I am working on setting up ApolloGateway, but can't seem to figure out how to plug it into the workers-graphql-server.

Has anyone done something similar?

Following: https://github.com/apollographql/federation-demo
Reference: https://www.apollographql.com/docs/apollo-server/federation/introduction/

My long term goal is:

  1. ApolloGateway worker on my base domain
  2. External GraphQL API
  3. Standard GraphQL worker pointing to a REST API
  4. Standard GraphQL worker pointing to Neo4j GraphQL

I am currently working on No. 1 connecting to No. 2. I have a somewhat working No. 4 locally, haven't refactored it into a worker yet.

Any advice, examples, or words of encouragement is greatly appreciated!

PS - I'm willing to create a workers-graphql-gateway-server template to work alongside this project.

KV caching does not appear to work

hey @codewithkristian and team! Looks like the KVCache mechanism isn't working as described (or at least I'm not able to use it with the docs provided). I've set the ID properly and I can confirm I'm setting values with that ID via Wrangler, but when I run it in a worker, nothing ever shows up in the KV cache storage.

Is there a specific ttl header I need to set when I'm hitting this server to get the content cached? It's not easy to debug and I'm unclear how I can see what's happening inside kv-cache.js when the worker is running. Thanks in advance!

Typescript support

I am currently trying to set up a TypeScript version of this template but I can't make it work with webpack. It would be cool if someone could help me with that or provide a guide in the readme on how to do it. Thanks in advance!

Does this work with `wrangler preview`?

image
image

I can successfully preview the project, but hitting a wall when trying to contact the apollo server - the error that comes back seems to indicate a problem intrinsic to cloudflare worker previews?

Any way to reduce bundle size?

Pretty surprised at the bundle size here, I'm seeing 1.5MB raw, 400k gzipped for a fresh clone and wrangler build of this repo. Is that just Apollo being enormous?

For the purposes of this project, is there something we can do to either strip out a bunch of Apollo stuff or use an alternative implementation?

Using makeRemoteExecutableSchema while importing a bigger local schema json file does not work

Hello,
It was fun playing around with this repo. It's very promising. Indeed I've been trying out this server with no issues using simple examples.

However, as soon as I started trying using remote schemas by loading a local json file I had some issues I've described here.

Although this it's not probably related to your work, I was wondering if you can have a look at the issue anyway and give your feedback. You'll also find a repo reproducing the issue.

Thanks.

Unable to generate, unknown variable

Basically the .github build is breaking using wrangler generate.

wrangler generate my-data-api https://github.com/signalnerve/workers-graphql-server                                                                                                                 
🔧   Creating project called `my-data-api`...
Error: ⛔   Error replacing placeholders `/Users/kokarn/repos/my-data-api/.github/workflows/deploy.yml`
Info: caused by liquid: Unknown variable
  with:
    requested variable=secrets
    available variables=authors, crate_name, project-name

TypeScript support, build too large

Hi Kris, I've been working on adding TypeScript support but I'm struggling with Wrangler not building correctly.

The only way I got it to build is by mocking modules in the webpack config like this to get the Apollo stuff to work

resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    alias: {
      fs: path.resolve(__dirname, './src/utils/empty.ts'),
      busboy: path.resolve(__dirname, './src/utils/empty.ts'),
    },
  }

But this build is 2MiB so it can't get uploaded. Setting it to production mode also didn't help.

I also think that the way we're importing stuff from Apollo is a bit weird, I think Apollo should provide a nice interface that builds and compiles just fine instead of having to wrap the server in a function imported from dist. There's this issue for example that kinda leaves me scratching my head.

I have a simpler TypeScript repo that runs and deploys just fine.

If I get this to work, my plan is to convert a medium-sized codebase to Cloudflare workers. You got any pointers on where I can take this?

Unable to use Apollo Graph Manager

When deploying a version of the GraphQL server that has the Apollo Engine config provided:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  engine: {
    apiKey: "abc123",
    schemaTag: "production"
  }
});

Any executed queries return the error:

{
  "error": {
    "errors": [
      {
        "message": "[internal apollo-server error] addProtobufError called before startTiming!",
        "extensions": {
          "code": "INTERNAL_SERVER_ERROR"
        }
      }
    ]
  }
}

I found this issue apollographql/apollo-server#3627 which seems to document this, but bumping to a specific version as specified in that ticket didn't resolve the error.

Move logic from `apollo-server-cloudflare` to this repo with Apollo Server 4?

Hi! We're starting our work on Apollo Server 4. You can see details in our full roadmap but the overview is that instead of shipping Apollo Server with 9 core-maintained integrations with web frameworks and serverless environments (but providing no means for adding more integrations), we will provide a stable API for anyone to provide an integration with their favorite web environment (essentially an abstract representation of HTTP requests and responses). We will continue to actively maintain HTTP handlers that work with Node's built-in http objects (including an Express-style middleware) but we will be shifting integrations with other web environments to community-maintained.

One of those 9 currently-core-maintained integrations is apollo-server-cloudflare, which is used by this project. It consists of a small amount of code that registers a fetch event listener and converts between fetch-style requests and the type that Apollo Server 3 understands. As you may have noticed, this hasn't been particularly actively maintained since its creation over three years ago, and it's one of the integrations that we will be transitioning to community maintenance.

We've opened an issue on our repo looking for folks interested in maintaining the AS4 version of this package. That said, as far as we know the only reason people end up using apollo-server-cloudlfare is because they're using this quickstart. So one possibility might be that we can get rid of apollo-server-cloudflare entirely and write the glue code directly in this repository. (Note that one of the goals for AS4 is that the glue code should end up a lot simpler than the existing glue code, which itself is under a hundred lines of code.)

Does that make sense as an alternative?

KV binding is deleted on new deploys

via #2

deploying a new version of the worker via serverless kills the KV binding. i think this is a serverless/deploy issue, and can be manually fixed post-deploy in the UI (but this sucks)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.