Using GraphQL to Create Blogs with Image Uploads in MongoDB
Using GraphQL to Create Blogs with Image Uploads in MongoDB
To implement blog creation with image uploads, we’ll use Apollo Server for GraphQL, MongoDB for data storage, and GridFS for handling binary file storage. Follow the steps below for seamless integration.
Prerequisites
Install the required dependencies using Yarn:
yarn add apollo-server graphql multer graphql-upload mongodb |
Enable file uploads in Apollo Server with the graphql-upload package.
Implementation
1. Setup Apollo Server with File Uploads
const resolvers = { Upload: GraphQLUpload, Mutation: { createBlog: async ( _: any, { title, content, image }: { title: string; content: string; image?: FileUpload } ) => { let imageId = null; if (image) { const { createReadStream, filename, mimetype } = await image; const stream = createReadStream(); imageId = await new Promise((resolve, reject) => { const uploadStream = bucket.openUploadStream(filename, { contentType: mimetype }); stream.pipe(uploadStream); uploadStream.on(“finish”, () => resolve(uploadStream.id.toString())); uploadStream.on(“error”, reject); }); } const blog = { title, content, imageId, createdAt: new Date().toISOString(), }; // Assume `saveBlog` is a function to insert data into MongoDB or another database const result = await saveBlog(blog); return { id: result.id, …blog }; }, }, }; |
Explanation
GraphQL Schema
- Upload Scalar: Handles file uploads using the graphql-upload package.
- createBlog Mutation: Accepts title, content, and an optional image file.
- blogs Query: Retrieves all blog posts with their metadata.
Resolvers
- createBlog Mutation:
- Processes the image file using createReadStream and stores it in MongoDB GridFS.
- Saves the blog metadata (title, content, and imageId) in the blogs collection.
- blogs Query:
- Fetches all blogs from MongoDB and returns them, including the imageId.
MongoDB GridFS
- Manages uploaded files in binary format.
- Generates a unique imageId for each file, stored alongside blog metadata.
Apollo Server
- Configured to support file uploads using graphql-upload.
Postman Operations
Mutation Name:
createBlog
Description:
The createBlog mutation allows you to create a blog post with the following parameters:
- title (String, required): Title of the blog post.
- content (String, required): Content of the blog post.
- image (Upload, optional): An optional image file for the blog.
Mapping Example (Variables Section):
{ “map”: { “”: [“variables.file”] } } |
File Input (Index 0):
Map the file being uploaded as “variables.file”, specifying its name in Postman’s file upload section.
Retrieving Blogs
Query:
query GetBlogs { blogs { id title content imageId createdAt } } |
Description:
This query retrieves all blog posts, including their metadata such as title, content, imageId, and createdAt.