Skip to content

Commit d77f8fd

Browse files
committed
Update created blog route
1 parent 528264c commit d77f8fd

1 file changed

Lines changed: 23 additions & 20 deletions

File tree

src/app/api/blog/create/route.ts

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import { NextResponse } from "next/server";
22
import { v2 as cloudinary } from "cloudinary";
3-
import { writeFile } from "fs/promises";
4-
import path from "path";
53
import Blog from "@/models/blogModel";
64
import dbConnect from "@/dbConfig/dbConfig";
75

@@ -14,9 +12,9 @@ cloudinary.config({
1412
export async function POST(req: Request) {
1513
try {
1614
await dbConnect(); // Connect to MongoDB
15+
1716
const formData = await req.formData();
18-
// console.log(formData)
19-
17+
2018
const username = formData.get('username');
2119
const title = formData.get("title") as string;
2220
const category = formData.get("category") as string;
@@ -27,32 +25,37 @@ export async function POST(req: Request) {
2725
return NextResponse.json({ error: "All fields are required" }, { status: 400 });
2826
}
2927

30-
// Convert File to Buffer
31-
const bytes = await imageFile.arrayBuffer();
32-
const buffer = Buffer.from(bytes);
33-
34-
// Save Image Locally (Optional)
35-
const uploadPath = path.join(process.cwd(), "public/uploads", imageFile.name);
36-
await writeFile(uploadPath, buffer);
37-
38-
// ✅ Upload Image to Cloudinary
39-
const cloudinaryResponse = await cloudinary.uploader.upload(uploadPath, {
40-
folder: "blog-images",
41-
});
42-
43-
// Save Blog to MongoDB
28+
const arrayBuffer = await imageFile.arrayBuffer();
29+
const buffer = Buffer.from(arrayBuffer);
30+
31+
// Upload buffer directly to Cloudinary
32+
const uploadFromBuffer = () =>
33+
new Promise((resolve, reject) => {
34+
const stream = cloudinary.uploader.upload_stream(
35+
{ folder: "blog-images" },
36+
(error, result) => {
37+
if (error) reject(error);
38+
else resolve(result);
39+
}
40+
);
41+
stream.end(buffer);
42+
});
43+
44+
const cloudinaryResult = await uploadFromBuffer();
45+
46+
// Save blog to MongoDB
4447
const newBlog = new Blog({
4548
username,
4649
title,
4750
category,
4851
content,
49-
imageUrl: cloudinaryResponse.secure_url,
52+
imageUrl: (cloudinaryResult as any).secure_url,
5053
});
5154

5255
await newBlog.save();
5356

5457
return NextResponse.json({ message: "Blog created successfully", blog: newBlog }, { status: 201 });
55-
} catch (error: unknown) {
58+
} catch (error) {
5659
console.error("Error creating blog:", error);
5760
return NextResponse.json({ error: "Failed to create blog" }, { status: 500 });
5861
}

0 commit comments

Comments
 (0)