Getting started with serverless (offline) and GraphQL-API

Table of Content

In this tutorial I will explain step-by-step how to get started with your first serverless project using TypeScript and a GraphQL API in a local(offline) development environment by using the serverless offline-plugin.

What you need:

  • node.js (version 13)
  • a Text-Editor or a source-code-editor like Visual Studio Code
  • serverless installed
  • a terminal in which you can enter your commands (Visual Studio Code already ships with a terminal)
  • A running version of this tutorial

Step 1: Installing apollo-server-express and graphql

Install these 2 packages with the following command.

npm i --save apollo-server-express graphql

Step 2: Change index.ts

Open index.ts in your src-folder and open it for editing in your favorite text-editor or IDE.
Replace the content with the code below and save the file.

import serverless from 'serverless-http';
import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';

// define a query which returns a String
const typeDefs = gql`
    type Query {
        hello: String
    }
`;

// implement the resolver which returns the data
const resolvers = {
    Query: {
        hello: () => 'Hello World!',
    },
};

// create the ApolloServer (with type definitions and resolvers)
// activate introspection for schemas
// activate playground (this way we can test our api)
// give the subscriptions a path
const server:ApolloServer = new ApolloServer({ typeDefs, resolvers,
                                    introspection: true, playground: true,
                                    subscriptions: {path: '/api'},
                                });

// create the express server
const app:express.Application = express();

// add the apollo-server to the express-server with path "/api" and activate cors
server.applyMiddleware({ app, path: "/api", cors: true });

module.exports.api = serverless(app);

As you can see it’s still an express-server, but this time it uses the apollo-server-middleware.

Step 3: Run the example

Now we can run the example.

$ npm start

Navigate your browser to http://localhost:3000/api and you will see the GraphQL-Playground.

Execute the following GraphQL-Query to check if you get a response without an error:

{
  hello
}

You should get this JSON-Response:

{
  "data": {
    "hello": "Hello World!"
  }
}

That’s it!

Best Page Builder Plugin
Best Digital Asset Library
Find amazing stock images
Feel free to leave a comment
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x