What are your thoughts?
Hi, first of all. I really appreciate your work. Thank you for your tutorial. Also, I wanted to know how the buildSchema.js works. I mean, I don’t see where is it call when I start muy build script. Can you explain a little how it works? Thanks in ad...
Great post, very helpful. Had to look up the health check endpoint, but that’s fine. When does the buildSchema script get called? You mention adding it the the yarn build script, but you don’t seem to go back and do that. Running it on it’s own I get some errors because the data folder doesn’t exist.
At least one example how to use the playground would be nice. I have to get this information elsewhere, which feels like an anti-climax when reaching the end of the article. Besides that, good article.
You have 1 free member-only story left this month. Upgrade for unlimited access.
Create a GraphQL API With Node.js, Mongoose, and Express
Get started with GraphQL, and build your first API.
GraphQL is a technology that helps developers build robust software more quickly. The ability to request all of the information you need in a single request is a game changer.
It has simplified the back-end development of APIs for consumption by mobile and web applications that would normally rely on RESTful APIs. A normal RESTful API may have several end points for various entities (e.g., users, submissions, etc.); with GraphQL, you can get all of this information in a single go using GraphQL’s query language, also known as GQL.
In this tutorial, I’ll walk you through how to build a GraphQL API with graphql-compose-mongoose, as well as a few other tools. And, of course, everything will be to ES6 spec using Node.js. If this sounds like an exciting adventure, read on.
To get started, we’ll need to double-check you have a few prerequisites to ensure both that you understand the technology and that you can complete the tutorial in full.
- Node.js (Latest 13.x or above)
- Yarn (brew install yarn on macOS)
- An account with MongoDB Atlas or a local instance of MongoDB running
To start, create a new directory.
You can name your directory whatever you would like; for this tutorial, we’re going to create a to-do application, so I called mine todo.
Next, let’s go ahead and generate our package.json file using Yarn. We’ll add modules, as necessary, as we continue to move forward.
Note: Answer the questions as prompted. Nothing necessarily required here — just whatever you’d like to set as your defaults.
- Make a src directory
- Move into the src directory
- Generate schema, models, scripts, and utils directories
Lastly, we’ll create an index.js file, which will allow us to import our dependent files and directories:
Inside of index.js, place the following contents, and save:
Now that we have the base files in place, let’s go ahead and add the required production packages to our package.json file using Yarn, like so:
And for development packages, add the following:
Now that we have the necessary packages installed, we can modify our package.json file to allow for additional functionality.
Let’s modify it to add scripts and hooks; once we’ve done that, your package.json file should look much like this:
The below will allow us to run scripts via Yarn (e.g., yarn <INSERT SCRIPT HERE>). For example, we can lint our code using yarn lint, and it’ll perform ESLint and Prettier operations on our files.
Similar to above, we’ll add a Husky script that will trigger on the precommit event, effectively running yarn lint for us prior to committing code.
This is an excellent practice for maintaining quality, clean code:
That’s all for scripts. Let’s continue on.
Configuring Babel, Prettier, and ESLint
We’ve taken the necessary steps to install the correct packages for Babel, Prettier, and ESLint.
Now, it’s time to add the configuration files to the root of your project. Move the root, and add the following files:
Perfect! We’re making progress.
Onto the next section.
Creating Our Models
The reason I enjoy working with graphql-compose-mongoose is that it allows me to use Mongoose models rather than writing GraphQL models by hand (which, by the way, can become quite cumbersome on a large application).
Head over to src/models, and create a new file named user.js. Inside this file, we’ll define all of the required characteristics that make up a user. This will be a small file, but feel free to add additional information to the user record if you wish (for example, a password using mongoose-bcrypt).
Next, let’s create a task.js file (given that this is, after all, a to-do GraphQL API):
We now have two models/schemas: UserSchema and TaskSchema.
A user is an individual entity, and a task always belongs to a user. From this, we will eventually be able to pull all tasks for a user in a single GraphQL call. Pretty cool, right?
Creating Our Schemas
Schemas are an interesting part of this implementation. They, essentially, allow us to define what calls can and cannot be made to the server.
Schemas are made up of queries and mutations, where queries allow you to fetch data, and mutations allow you to modify data. Let’s create our schemas for both the user and task model.
Inside of the schema directory, create a file called user.js. Then, drop the following contents into the file:
Next, let’s create one called task.js:
To tie things together, we’ll generate an index.js file in the root of the directory (src/schema) and import our schemas:
Now that we have full CRUD capabilities with GraphQL, let’s add our final utilities.
The build script allows you to transform your Mongoose-style schemas into pure GraphQL schemas. Pretty fancy, huh?
Create a file called buildSchema.js inside of src/scripts, and drop the following code in:
This file will be called with the yarn build command and will output the raw GraphQL queries into a data directory.
What’s an API without a database? That’s why we’ll need to create a connection from Mongoose to MongoDB.
If you haven’t already created a .env file in the root directory, now’s the time to do so. You’ll want to ensure it has the following environment variables:
Once your .env file’s in place, let’s go ahead and create another file inside of src/utils. Name the file db.js, and add the following contents:
Note: If you don’t have MongoDB up and running locally, MongoDB Atlas is a great alternative. Not only is it free, but it packs enough power on the free tier to run a development application without any issues. Check it out here.
Your GraphQL is now complete. Run the command yarn dev, and you’ll be able to spin up the playground for GraphQL, which allows you to add, modify, remove, and query users and tasks — all in one call.
It looks a little something like this:
This quick-and-dirty tutorial is just the beginning of all the fun you can have using GraphQL to make your development stronger, cleaner, and more efficient.
Try expanding on what you’ve just built to add additional functionality to the models, or venture out on your own to improve one of your existing applications — or even spin up a new one; I’d love to hear more about all that you decide to do.
Until then, thank you for following me along throughout this tutorial, and stay tuned for future updates. Happy coding!
Advice for programmers.
Technical Writer🖋 Coder 👨💻 Outdoor Enthusiast 🏔️ Wannabe Astronaut 👨🚀 https://nickparsons.io 🔗
Advice for programmers.
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade