Skip to content

Commit

Permalink
4 controller added
Browse files Browse the repository at this point in the history
  • Loading branch information
zobkazi committed Jun 15, 2024
1 parent 860ee96 commit 7434306
Show file tree
Hide file tree
Showing 24 changed files with 398 additions and 133 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.4.1",
"morgan": "^1.10.0",
"nodemailer": "^6.9.13",
"swagger-ui-express": "^5.0.1",
"winston": "^3.13.0",
"winston-mongodb": "^5.1.1",
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/category/create.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const Category = require('../../models/category/Category');
const { categorySchema } = require('../../schemas/category/CategorySchema');

const createCategory = async (req, res, next) => {
const create = async (req, res, next) => {
try {
// Validate request body
const parsedBody = categorySchema.safeParse(req.body);
Expand Down Expand Up @@ -38,4 +38,4 @@ const createCategory = async (req, res, next) => {
}
};

module.exports = createCategory;
module.exports = create;
42 changes: 42 additions & 0 deletions src/controllers/category/getAll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const Category = require('../../models/category/Category');

const getAll = async (req, res, next) => {
try {
const limit = parseInt(req.query.limit, 10) || 10; // Number of items per page
const nextCursor = req.query.next || null; // Cursor for the next page
const prevCursor = req.query.prev || null; // Cursor for the previous page

let query = {};
if (nextCursor) {
query._id = { $gt: nextCursor };
} else if (prevCursor) {
query._id = { $lt: prevCursor };
}

// Fetch categories with pagination
const categories = await Category.find(query)
.limit(limit)
.sort({ _id: 1 });

// Construct next and previous links
const nextLink = categories.length > 0
? `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}?limit=${limit}&next=${categories[categories.length - 1]._id}`
: null;

const prevLink = categories.length > 0
? `${req.protocol}://${req.get('host')}${req.baseUrl}${req.path}?limit=${limit}&prev=${categories[0]._id}`
: null;

// Return success response with the categories and pagination links
return res.status(200).json({
success: true,
data: categories,
next: nextLink,
prev: prevLink
});
} catch (error) {
next(error);
}
};

module.exports = getAll;
Empty file.
11 changes: 8 additions & 3 deletions src/controllers/category/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
const createCategory = require("./create");

const create = require("./create");
const getAll = require("./getAll");
const update = require("./update");
const remove = require("./remove");

module.exports = {
createCategory
create,
getAll,
update,
remove
}


Expand Down
28 changes: 28 additions & 0 deletions src/controllers/category/remove.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const Category = require('../../models/category/Category');

const remove = async (req, res, next) => {
try {
// Check if category exists
const category = await Category.findById(req.params.id);
if (!category) {
return res.status(404).json({
success: false,
message: "Category not found",
});
}

// Delete category
await category.remove();

// Return success response
return res.status(200).json({
success: true,
message: "Category deleted successfully",
});

} catch (error) {
next(error);
}
};

module.exports = remove;
41 changes: 41 additions & 0 deletions src/controllers/category/update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const Category = require('../../models/category/Category');
const { categorySchema } = require('../../schemas/category/CategorySchema');

const update = async (req, res, next) => {
try {
// Validate request body
const parsedBody = categorySchema.safeParse(req.body);
if (!parsedBody.success) {
return res.status(400).json({
success: false,
message: "Invalid request body",
errors: parsedBody.error.errors,
});
}

// Check if category exists
const category = await Category.findById(req.params.id);
if (!category) {
return res.status(404).json({
success: false,
message: "Category not found",
});
}

// Update category with new data
Object.assign(category, parsedBody.data);
await category.save();

// Return success response with the updated category
return res.status(200).json({
success: true,
message: "Category updated successfully",
data: category
});

} catch (error) {
next(error);
}
};

module.exports = update;
90 changes: 48 additions & 42 deletions src/controllers/comment/create.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,52 @@
const Comment = require("../../models/comment/Comment");
const { commentSchema } = require("../../schemas/comment/CommentSchema");

const create = async (req, res, next) => {
try {

// validate request body
const parsedBody = commentSchema.safeParse(req.body);

if (!parsedBody.success) {
return res.status(400).json({
success: false,
message: "Invalid request body",
errors: parsedBody.error.errors,
});
}

// check if Comment already exists
const existingComment = await Comment.findOne({ comment: parsedBody.data.comment });
if (existingComment) {
return res.status(400).json({
success: false,
message: "Comment already exists",
});
}


const validateRequestBody = (body) => {
const parsedBody = commentSchema.safeParse(body);
if (!parsedBody.success) {
const error = new Error("Invalid request body");
error.status = 400;
error.details = parsedBody.error.errors;
throw error;
}
return parsedBody.data;
};

const checkIfCommentExists = async (commentText) => {
const existingComment = await Comment.findOne({ comment: commentText });
if (existingComment) {
const error = new Error("Comment already exists");
error.status = 400;
throw error;
}
};

const createComment = async (data) => {
const comment = new Comment(data);
await comment.save();
return comment;
};

// create new comment
const comment = new Comment(parsedBody.data);
await comment.save();


// Return success response with token
return res.status(201).json({
success: true,
message: "Comment created successfully",
data: comment
});
} catch (error) {
next(error);
}
}


module.exports = create;
const create = async (req, res, next) => {
try {
const requestBody = validateRequestBody(req.body);
await checkIfCommentExists(requestBody.comment);
const newComment = await createComment(requestBody);

return res.status(201).json({
success: true,
message: "Comment created successfully",
data: newComment,
});
} catch (error) {
if (!error.status) error.status = 500;
res.status(error.status).json({
success: false,
message: error.message,
errors: error.details || [],
});
next(error);
}
};

module.exports = create;
92 changes: 60 additions & 32 deletions src/controllers/comment/getAll.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,78 @@
const logger = require("../../utils/logger");
const Comment = require("../../models/comment/Comment");

const comments = async (req, res, next) => {
try {
// Pagination parameters
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;

const getAll = async (req, res, next) => {
logger.info("Fetching all comments");
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;

// Fetch paginated comments from the database
const comments = await Comment.find()
.skip(skip)
.limit(limit);
try {
// Calculate pagination values
const startIndex = (page - 1) * limit;
const endIndex = page * limit;

// Total number of pages
const totalPages = Math.ceil(await Comment.countDocuments() / limit);
// Fetch total count of comments (for pagination metadata)
const totalComments = await Comment.countDocuments();

// Previous page
const previousPage = page > 1 ? page - 1 : null;
// Log pagination details
logger.info(`Total comments: ${totalComments}`);
const totalPages = Math.ceil(totalComments / limit);
logger.info(`Total pages: ${totalPages}`);
logger.info(`Current page: ${page}`);
logger.info(`Limit: ${limit}`);
logger.info(`Start index: ${startIndex}`);

// Next page
const nextPage = page < totalPages ? page + 1 : null;
// Query comments with pagination and limit
const comments = await Comment.find().skip(startIndex).limit(limit);

// Current page
const currentPage = page;
// Log successful retrieval of comments
logger.info(`Comments retrieved successfully`, { count: comments.length });


// Prepare pagination metadata
const pagination = {
currentPage: page,
limit: limit,
totalItems: totalComments,
};

// Total number of comments
const totalCount = await Comment.countDocuments();
// Add pagination links
const baseUrl = `${req.protocol}://${req.get("host")}${req.baseUrl}${
req.path
}`;
if (endIndex < totalComments) {
pagination.nextPage = {
page: page + 1,
limit: limit,
url: `${baseUrl}?page=${page + 1}&limit=${limit}`,
};
}
if (startIndex > 0) {
pagination.prevPage = {
page: page - 1,
limit: limit,
url: `${baseUrl}?page=${page - 1}&limit=${limit}`,
};
}

res.status(200).json({
// Return success response with comments and pagination metadata
return res.status(200).json({
success: true,
message: "Comments fetched successfully",
pagination: {
total: totalCount,
page: currentPage,
pages: totalPages,
previous: previousPage,
next: nextPage,
},
message: "Comments retrieved successfully",
pagination: pagination,
data: comments,
});
} catch (error) {
// Log the error
logger.error("Failed to retrieve comments", { error: error.message });

// Handle errors
res.status(500).json({
success: false,
message: "Failed to retrieve comments",
errors: error.message,
});
next(error);
}
};

module.exports = comments;
module.exports = getAll;
10 changes: 5 additions & 5 deletions src/controllers/comment/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const remove = require("./remove");
const update = require("./update");

module.exports = {
create,
comments,
remove,
update
}
create,
comments,
remove,
update,
};
Loading

0 comments on commit 7434306

Please sign in to comment.