Serverless with GraphQL

Serverless

Take a deep dive into the Serverless framework with AWS Lambda and NodeJS. It’s much easier than you think!

The serverless framework allows you to build out applications without having to think about the box, or server, that it runs on. Instead, you simply write stateless functions that would handle incoming requests. This really allows for the decomposition of monolithic applications into smaller pieces, known as micro services.

GraphQL

Facebook launched GraphQL not too long ago, and it is catching on pretty quickly. Traditionally, most APIs are written in a REST style, but there are some drawbacks. GraphQL solves most, if not all, of these problems with it’s custom query language.

Serverless + GraphQL

Putting GraphQL and Serverless together can result in a very powerful application. In the end, one GraphQL endpoint can replace an entire API. Let’s take a look at the code, below.

Setup

We’ll be using npm and Node.js in this tutorial, so make sure they are setup properly on your machine. For the serverless side, we’ll be using AWS Lambda as the provider.

Project Setup

Make a directory with your preferred name for this project. For example:

mkdir sls-graphql

Install Serverless

To install serverless globally, run the following command:

npm install -g serverless

We’ll use serverless-offline to run our code locally:

npm install --save-dev serverless-offline

Then, create a new serverless service with:

serverless create --template aws-nodejs --path graphql-service

Once inside the service directory, initialize an npm project and follow through the steps:

npm init

We’re also going to have to provide GraphQL with a schema, so let’s create a file for it:

touch schema.js

Install GraphQL

Now, add GraphQL to the project:

npm install --save graphql@0.10.1

We’ll also need a helper library, called graphql-server-lambda:

npm install --save graphql-server-lambda@0.8.0

Project Structure

The project directory, should now look like this:

graphql-service
|-- .gitignore
|-- serverless.yml
|-- handler.js
|-- package.json
|-- node_modules/

Wiring It Up With Code

The serverless.yml file is how we will configure our serverless functions. For this tutorial, we’ll be setting up two endpoints:

  • POST /graphql
  • GET /graphiql

So, our serverless.yml file, should look like this:

service: graphql-service
provider:
  name: aws
  runtime: nodejs6.10
  stage: dev
  region: us-east-1
package:
  include:
    - node_modules/**
    - schema.js

plugins:
  - serverless-offline

functions:
  graphql:
    handler: handler.graphql
    events:
      - http:
          path: graphql
          method: post
          cors: true
  graphiql:
    handler: handler.graphiql
    events:
      - http:
          path: graphiql
          method: get

Starting from the top, we have set up our serverless function to run on AWS in a dev environment. We include the node_modules/ directory and the schema.js file, since our functions will depend on code in those files. We also set up our plugin to test our functions locally. And lastly, we set up our functions.

The handlers in our yml files point to functions defined in the handler.js file. So, we must provide two functions:

  • graphql()
  • graphiql()

Using the helper library, we can define our handler.js file, as below:

const server = require('graphql-server-lambda')
const schema = require('./schema')

module.exports.graphql = server.graphqlLambda({ schema })
module.exports.graphiql = server.graphiqlLambda({ endpointURL: '/graphql' })

Now all that’s left is defining our GraphQL schema! Here’s a sample schema:

const { GraphQLObjectType, GraphQLSchema, GraphQLString } = require('graphql')

const query = new GraphQLObjectType({
  name: 'Query',
  description: 'The root query of the schema',
  fields: () => ({
    hello: {
      type: GraphQLString,
      resolve: () => 'world!'
    }
  })
})

module.exports = new GraphQLSchema({ query })

Run Like the Wind

Everything should be ready to go now! So, while in the service, you can run:

serverless offline start

This will run the spin up the server locally, and let you know the port number. Usually, it’s 3000. If you head over to http://localhost:3000/graphiql, you should see the GraphiQL GUI where you can test your schema with.

For example, with the sample schema above, if you enter:

query {
  hello
}

The output should look like:

{
  "data": {
    "hello": "world!"
  }
}

That’s it! You’re all set up with GraphQL and Serverless!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: