Skip to content

Commit

Permalink
mongodb+srv:
Browse files Browse the repository at this point in the history
  • Loading branch information
zobkazi committed Jul 5, 2024
1 parent 04076c0 commit 75ea52f
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 137 deletions.
110 changes: 58 additions & 52 deletions src/app/api/blogs/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,60 @@
// import Blog from "@/models/blog/Blog";
// import { NextResponse, NextRequest } from "next/server";
// import dbConnect from "@/utils/dbConnection";
// import { Types } from "mongoose";
// import { blogSchema } from "@/schemas/blogSchema";

// interface Params {
// params: {
// id: string;
// };
// }

// // get notice by id
// export async function GET(request: NextRequest, { params }: Params) {
// try {
// // Connect to the database
// await dbConnect();

// // Get the ID from the request params
// const { id } = params;

// console.log(params.id);

// // Check if the ID is a valid ObjectId
// if (!Types.ObjectId.isValid(id)) {
// return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
// }

// // Fetch the notice by ID from the database
// const notice = await Blog.findById(id);

// // Check if the notice exists
// if (!notice) {
// return NextResponse.json({ error: "Blog not found" }, { status: 404 });
// }

// // Respond with the fetched notice
// return NextResponse.json({ notice });
// } catch (error) {
// // Log the error for debugging purposes
// console.error("Error fetching Blog:", error);

// // Respond with an error message
// return NextResponse.json(
// { error: "Internal Server Error" },
// { status: 500 }
// );
// }
// }

// // update notice
import Blog from "@/models/blog/Blog";
import { NextResponse, NextRequest } from "next/server";
import dbConnect from "@/utils/dbConnection";
import { Types } from "mongoose";
import { blogSchema } from "@/schemas/blogSchema";

interface Params {
params: {
id: string;
};
}

// get notice by id
export async function GET(request: NextRequest, { params }: Params) {
try {
// Connect to the database
await dbConnect();

// Get the ID from the request params
const { id } = params;

console.log(params.id);

// // Check if the ID is a valid ObjectId
// if (!Types.ObjectId.isValid(id)) {
// return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
// }

// // Fetch the notice by ID from the database
// const notice = await Blog.findById(id);

// // Check if the notice exists
// if (!notice) {
// return NextResponse.json({ error: "Blog not found" }, { status: 404 });
// }

// Respond with the fetched notice
return NextResponse.json({
success: true,
message: "Blog fetched successfully",
data: {
// notice,
}
});
} catch (error) {
// Log the error for debugging purposes
console.error("Error fetching Blog:", error);

// Respond with an error message
return NextResponse.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
}

// update notice

// export async function PUT(request: NextRequest, { params }: Params) {
// try {
Expand Down Expand Up @@ -95,4 +101,4 @@
// }
// }

// // delete notice
// delete notice
71 changes: 3 additions & 68 deletions src/app/api/blogs/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,76 +8,11 @@ export async function GET(request: NextRequest) {
try {
await dbConnect();

const url = new URL(request.url);
const query = url.searchParams;

const page = parseInt(query.get("page") || "1", 3);
const limit = parseInt(query.get("limit") || "10", 3);
const skip = (page - 1) * limit;

const filter = query.get("filter")
? JSON.parse(query.get("filter") as string)
: {};
const sort = query.get("sort")
? JSON.parse(query.get("sort") as string)
: {};
const search = query.get("search") || "";

const aggregationPipeline: any[] = [];
if (search) {
aggregationPipeline.push({
$match: {
$or: [
{ title: { $regex: search, $options: "i" } },
{ desc: { $regex: search, $options: "i" } },
],
},
});
}

if (Object.keys(filter).length) {
aggregationPipeline.push({ $match: filter });
}

aggregationPipeline.push({ $skip: skip });
aggregationPipeline.push({ $limit: limit });

if (Object.keys(sort).length) {
aggregationPipeline.push({ $sort: sort });
}

const totalBlogs = await Blog.countDocuments(filter);
const blogs = await Blog.aggregate(aggregationPipeline)
.project({
_id: 1,
title: 1,
desc: 1,
img: 1,
date: 1,
href: 1,
})
.exec();

const totalPages = Math.ceil(totalBlogs / limit);

const nextLink =
page < totalPages ? `/api/blogs?page=${page + 1}&limit=${limit}` : null;
const prevLink =
page > 1 ? `/api/blogs?page=${page - 1}&limit=${limit}` : null;

const blogs = await Blog.find();
return NextResponse.json({
success: true,
data: {
blogs,
pagination: {
totalBlogs,
totalPages,
currentPage: page,
limit,
nextLink,
prevLink,
},
},
message: "Blogs fetched successfully",
data: blogs,
});
} catch (error) {
logger.error("Something went wrong", error);
Expand Down
34 changes: 17 additions & 17 deletions src/app/api/contact/all/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@ import dbConnect from "@/utils/dbConnection";
export async function GET(request: NextRequest) {
await dbConnect();

const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get("page") || "1", 10);
const limit = parseInt(searchParams.get("limit") || "10", 10);
// const { searchParams } = new URL(request.url);
// const page = parseInt(searchParams.get("page") || "1", 10);
// const limit = parseInt(searchParams.get("limit") || "10", 10);

const startIndex = (page - 1) * limit;
// const startIndex = (page - 1) * limit;

const totalDocs = await Contact.countDocuments();
const contacts = await Contact.find().skip(startIndex).limit(limit);
// const totalDocs = await Contact.countDocuments();
// const contacts = await Contact.find().skip(startIndex).limit(limit);

const nextPage = page < Math.ceil(totalDocs / limit) ? page + 1 : null;
const prevPage = page > 1 ? page - 1 : null;
// const nextPage = page < Math.ceil(totalDocs / limit) ? page + 1 : null;
// const prevPage = page > 1 ? page - 1 : null;

const result = {
totalDocs,
currentPage: page,
totalPages: Math.ceil(totalDocs / limit),
nextPage,
prevPage,
data: contacts,
};
// const result = {
// totalDocs,
// currentPage: page,
// totalPages: Math.ceil(totalDocs / limit),
// nextPage,
// prevPage,
// data: contacts,
// };

return NextResponse.json(result, { status: 200 });
return NextResponse.json({ success: true, message: "Contacts fetched successfully" }, { status: 200 });
}

0 comments on commit 75ea52f

Please sign in to comment.