Setting Up Apollo GraphQL (2.0) Server with Express and MongoDB

11526 VIEWS

· ·

GraphQL is an open source query language used to expose API endpoints to client applications. Unlike REST, GraphQL only returns required data based on the query. The GraphQL server serves as an interface between the client and application data sources, receiving client requests and fetching the necessary data.

GraphQL servers come in different flavors. The easiest way to get started is by using the Express web framework. This tutorial will guide you through building your own GraphQL server from scratch using ApolloServer.

A GraphQL server can be implemented in a variety of ways. However, Apollo Server 2.0 dramatically simplifies the API for building a GraphQL server, removing multiple layers of setup and dependencies that were required in earlier versions of Apollo Server(1.x). Apollo Server is a library that helps you connect a GraphQL client to any conventional Node.js server, regardless of which framework the server runs on (Express, Hapi, Sail, Koa, and so on).

Project setup

The project we’re creating here is a simple node application:

Initialize a node application - npm init -- yes

Install the required node packages:

npm install express apollo-server-express mongoose 

Express server

An Express server can be set up in three simple lines of code:

var express = require('express')
const app = express();
app.listen(8000 , ()=> {console.log("App started")})

Integrate Apollo Server

Apollo Server can be integrated by simply adding the single library:

...
const  { ApolloServer } = require('apollo-server-express');
	...

Previous versions of Apollo Server would require dependencies like bodyparser.

...
const app = express();
const schema = ...
const resolvers = ...

const server = new ApolloServer({
  typeDefs: schema,
  resolvers,
});

server.applyMiddleware({ app, path: '/graphql' });
...

Defining types (Schema)

Types in GraphQL are used to describe the structure and types of data returned by the API server. They also define the object field required for the server.

In the snippet below, two queries are defined — greet and users. The greet query will return data of the type String, denoted by greet : !String

And users returns an array of users denoted by users: [User]

The user field is defined in the typeDef

...
const schema = `
type Query {
 greet: !String,
 users :[User],
}

type User {
    id:String,
    email:String,
    password:String,
    companyId:String
}`
...

Resolvers

Resolvers are used to perform the action defined in the rooType schemas. Resolvers carry out queries and changes based on the request. As in the snippet below, the greet query is defined as a function that returns the string “Hello from GraphQl side” while the users query calls the function fetchData() which returns a user object array.

...
const resolvers = {
  Query: {
    greet: () => {
      return "Hello from GraphQl side"
    },
    users:()=>{
        return fetchData()
    }
   },
}

var  fetchData = ()=>{
return []
}
...

In this state, the app can be started. (A full version of the current state can be found at GitHub Gist.) Apollo Server comes with GraphQL Playground, a built-in client for consuming GraphQL APIs. It can be found by using a GraphQL API endpoint in a browser at http://localhost:8000/graphql.

Start the app - node index.js

Integrating the database

To create a full-stack GraphQL application, you’ll need to introduce a persistent data source.
A simple user scheme is created with Mongoose.

Then, instead of returning static data, the fetchdata method is modified to query MongoDB using the Mongoose find() method:

const userSchema = new mongoose.Schema({
    id: {
        type: String,
        required: true,
        unique: true,
      }, 
       email: {
        type: String,
        required: true,
        unique: true,
      },
    password: {
        type: String,
        required: true,
    },
    companyId: {
        type: String,
        required: true,
    }
});


userSchema.set('toObject', { virtuals: true });

var MUsers =  mongoose.model('User', userSchema);
var  fetchData = ()=>{
return MUsers.find()
}

Learning more and moving beyond this example

While this article does not discuss code structuring and other API methods, it introduces setting up a GraphQL server with Apollo and Express. A complete version of the code can be found from GitHub.


John Odey is a FrontEnd software developer who have strong passion for bringing conceptual ideas into real software solutions.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar