GraphQL Compose and GraphQL Compose Mongoose Simplified Tutorial
GraphQL Compose is a powerful toolkit for building scalable GraphQL schemas quickly and easily. It introduces a higher-level abstraction that simplifies defining GraphQL types, resolvers, and queries, making it much more efficient than the traditional approach. When combined with Mongoose, a MongoDB object modeling library, GraphQL Compose becomes even more potent in creating schemas for MongoDB, streamlining data modeling and schema creation.
In this tutorial, we’ll cover an introduction to GraphQL Compose, compare it to regular GraphQL development, discuss its benefits, and walk through creating a simple blog post API using GraphQL Compose and Mongoose.
What is GraphQL Compose?
GraphQL Compose is an open-source tool that simplifies creating and managing GraphQL schemas by introducing a more declarative way to define types, inputs, mutations, and queries. It helps reduce boilerplate code, allowing developers to focus on the logic of their application instead of repetitive schema definition tasks.
With GraphQL Compose Mongoose, GraphQL Compose integrates seamlessly with Mongoose, making it simple to build GraphQL APIs over MongoDB data sources by automatically mapping Mongoose models to GraphQL types and resolvers.
GraphQL Compose vs. Traditional GraphQL
Using vanilla GraphQL to create a schema can become verbose, especially for complex data models. You’d need to manually define GraphQL types, inputs, resolvers, and mutations. GraphQL Compose abstracts much of this by introducing helper functions and classes that reduce boilerplate code, making it easier to focus on building your API logic.
Feature | Traditional GraphQL | GraphQL Compose |
---|---|---|
Schema Definition | Manual type and resolver creation | Declarative, automatically generated resolvers |
Mongoose Integration | Requires custom integration | Automatic type and resolver creation from Mongoose |
Development Time | Longer, more boilerplate | Shorter, less code required |
Flexibility | High, but verbose | High, with better developer experience |
Benefits of Using GraphQL Compose
- Reduced Boilerplate: Simplifies schema creation, reducing the amount of code.
- Automatic Integration with Mongoose: Easily connects with Mongoose models, generating types and resolvers automatically.
- Modularity: Allows developers to create modular and reusable schema components.
- Enhanced Development Experience: Offers a simpler syntax and various helper functions, improving readability and reducing errors.
Tutorial: Creating a Blog Post API with GraphQL Compose and Mongoose
Let’s dive into creating a simple API for blog posts with GraphQL Compose, Mongoose, and MongoDB.
Step 1: Setting Up the Project
To get started, create a new Node.js project and install the necessary packages.
mkdir graphql-compose-blog
cd graphql-compose-blog
npm init -y
npm install express mongoose graphql graphql-compose graphql-compose-mongoose
Step 2: Connecting to MongoDB
Set up a MongoDB connection using Mongoose in index.js
.
const express = require('express');
const mongoose = require('mongoose');
const { ApolloServer } = require('apollo-server-express');
const { schemaComposer } = require('graphql-compose');
const app = express();
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Later, we will add schema and start the server here.
Step 3: Defining the Mongoose Model
Create a Mongoose schema and model for a blog post.
const { Schema, model } = require('mongoose');
const BlogPostSchema = new Schema({
title: { type: String, required: true },
content: { type: String, required: true },
author: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
});
const BlogPost = model('BlogPost', BlogPostSchema);
module.exports = BlogPost;
Step 4: Creating GraphQL Schema with GraphQL Compose and Mongoose
Now, let’s define the GraphQL schema using GraphQL Compose and GraphQL Compose Mongoose.
const { composeWithMongoose } = require('graphql-compose-mongoose');
const BlogPost = require('./models/BlogPost'); // Import the Mongoose model
// Convert Mongoose model to GraphQL type with GraphQL Compose Mongoose
const BlogPostTC = composeWithMongoose(BlogPost, {});
schemaComposer.Query.addFields({
blogPostById: BlogPostTC.getResolver('findById'),
blogPostMany: BlogPostTC.getResolver('findMany'),
});
schemaComposer.Mutation.addFields({
blogPostCreateOne: BlogPostTC.getResolver('createOne'),
blogPostUpdateById: BlogPostTC.getResolver('updateById'),
blogPostRemoveById: BlogPostTC.getResolver('removeById'),
});
In this code, composeWithMongoose
automatically converts the Mongoose BlogPost
model into a GraphQL type composer, allowing us to easily set up queries and mutations. The getResolver
method provides pre-built resolvers for common operations like findById
, findMany
, createOne
, updateById
, and removeById
.
Step 5: Starting the Apollo Server
To serve our GraphQL API, set up an Apollo Server with Express.
const server = new ApolloServer({
schema: schemaComposer.buildSchema(),
});
server.start().then(() => {
server.applyMiddleware({ app });
app.listen(4000, () => {
console.log(`Server is running at http://localhost:4000${server.graphqlPath}`);
});
});
Step 6: Testing the Blog Post API
With the server running, you can test your API by visiting http://localhost:4000/graphql
. Here are some sample queries and mutations to try:
- Create a Blog Post
mutation {
blogPostCreateOne(record: { title: "First Post", content: "This is the content", author: "Author Name" }) {
record {
_id
title
content
author
createdAt
}
}
}
- Fetch All Blog Posts
query {
blogPostMany {
_id
title
content
author
createdAt
}
}
- Fetch a Blog Post by ID
query {
blogPostById(_id: "BLOG_POST_ID_HERE") {
title
content
author
createdAt
}
}
- Update a Blog Post by ID
mutation {
blogPostUpdateById(_id: "BLOG_POST_ID_HERE", record: { title: "Updated Title" }) {
record {
_id
title
content
author
}
}
}
- Delete a Blog Post by ID
mutation {
blogPostRemoveById(_id: "BLOG_POST_ID_HERE") {
recordId
}
}
Conclusion
GraphQL Compose and GraphQL Compose Mongoose simplify building GraphQL APIs, making schema creation faster, especially with Mongoose. This approach reduces code complexity and enhances development speed, allowing you to focus on the core functionality of your app. By following this tutorial, you should have a working API for managing blog posts in a MongoDB database using GraphQL Compose and Mongoose.