In my last article, I gave a global introduction to GraphQL. I compared it with REST, as the two of them tend to do the same work, but there are some differences in term of quality and performance.

So in this article, we’re going to build a simple movie app, where we can show, add, edit, and delete movies. That way we’ll get through the basics of GraphQL, which is the main goal of this article — as I assume everyone reading this has already worked with NodeJS and MongoDB.

Creating Project and Installing Dependencies

First, you create a new project folder on your local disk. For instance, I have named mine graphql-tuto. In your Node command prompt, enter:

cd graphql-tuto
npm install express mongoose body-parser cors --save

Now we have installed Express, Mongoose, body-parser, and CORS. I’m not going to detail this since it’s not the main goal of this tutorial.

npm install apollo-server-express --save

From the Apollo Docs, I found that the “Apollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks,” such as Express.

So create a file namedapp.js. Add the following code to it to set up the Apollo Express Server and the MongoDB database.

const express = require('express');
const mongoose = require('mongoose');
const schema = require('./schema');
const bodyParser = require('body-parser');
const cors = require('cors');
const { ApolloServer } = require('apollo-server-express');
const url = "mongodb://localhost:27017/moviesdb";
const connect = mongoose.connect(url, { useNewUrlParser: true });
connect.then((db) => {
      console.log('Connected correctly to server!');
}, (err) => {
      console.log(err);
});
const server = new ApolloServer({
      typeDefs: schema.typeDefs,
      resolvers: schema.resolvers
});
const app = express();
app.use(bodyParser.json());
app.use('*', cors());
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
  console.log(`???? Server ready at http://localhost:4000${server.graphqlPath}`));

GraphQL has two main principles in order to work: types and resolvers. I defined them in Apollo Server. We’ll import them from the file we’ll create later.

#nodejs #graphql #mongodb #api

A Simple CRUD App using GraphQL, NodeJS and MongoDB
18.55 GEEK