Skip to content

Commit

Permalink
Add tag endpoints and controller
Browse files Browse the repository at this point in the history
  • Loading branch information
bewake24 committed Nov 18, 2024
1 parent cea1f01 commit 9deed44
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 33 deletions.
2 changes: 1 addition & 1 deletion constants/regex.constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const nameRegex = /^[A-Za-z]+(?: [A-Za-z]+)*$/;
const phoneRegex = /^\d{10}$/;

const cityRegex =
/^[a-zA-Z\u0080-\u024F]+(?:. |-| |')*([1-9a-zA-Z\u0080-\u024F]+(?:. |-| |'))*[a-zA-Z\u0080-\u024F]*$/;
/^[a-zA-Z\u0080-\u024F]+(?:[.\-'\s]*[a-zA-Z\u0080-\u024F]+)*$/;

const addressRegex =
/^(?:\d+|[a-zA-Z][a-zA-Z0-9\s,'-]*)\s[a-zA-Z0-9\s,'-]+(?:\s(?:Apt|Suite|Unit|#)\s?\d*[A-Za-z]?)?(?:,\s?[A-Za-z\s]+)?,\s?[A-Za-z]{2,}\s\d{5}(?:-\d{4})?$/;
Expand Down
64 changes: 33 additions & 31 deletions controllers/tag.controller.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
const Tag = require("../models/Tag"); // Assuming the Tag model is in the models directory
const ApiResponse = require("../utils/ApiResponse"); // Assuming ApiResponse is a utility function for handling responses
const {
MONGOOSE_DUPLICATE_KEY,
MONGOOSE_CAST_ERROR,
MONGOOSE_OBJECT_ID,
} = require("../constants/models.constants");
const Tag = require("../model/tag.model");
const ApiResponse = require("../utils/ApiResponse");

// Create a new tag
const createTag = async (req, res) => {
try {
const { name } = req.body;

// Check if the tag already exists
const existingTag = await Tag.findOne({ name });
if (existingTag) {
return ApiResponse.conflict(res, "Tag already exists", 409);
}

const tag = new Tag({ name });
await tag.save();
const tag = await Tag.create({ name });

ApiResponse.success(res, "Tag created successfully", tag);
} catch (error) {
ApiResponse.error(res, "Error while creating tag", error, 500);
if (error.code === MONGOOSE_DUPLICATE_KEY) {
return ApiResponse.conflict(res, "Tag already exists", 409);
}
ApiResponse.error(res, "Error while creating tag", 500, error);
}
};

// Get all tags
const getTags = async (req, res) => {
try {
const tags = await Tag.find();
ApiResponse.success(res, "Tags fetched successfully", tags);
ApiResponse.success(
res,
tags.length ? "Tags fetched successfully" : "Tags Not found",
tags
);
} catch (error) {
ApiResponse.error(res, "Error while fetching tags", error, 500);
}
};

// Get a single tag by ID
const getTagById = async (req, res) => {
const getATag = async (req, res) => {
try {
const { id } = req.params;

const tag = await Tag.findById(id);
const tag = await Tag.findOne(req.params);
if (!tag) {
return ApiResponse.notFound(res, "Tag not found", 404);
}
Expand All @@ -47,40 +47,42 @@ const getTagById = async (req, res) => {
}
};

// Update a tag by ID
const updateTag = async (req, res) => {
try {
const { id } = req.params;
const { name } = req.body;

// Check if the tag exists
const tag = await Tag.findById(id);
if (!tag) {
return ApiResponse.notFound(res, "Tag not found", 404);
}

// Check if the new name is already in use
const existingTag = await Tag.findOne({ name });
if (existingTag && existingTag._id.toString() !== id) {
return ApiResponse.conflict(res, "Tag name already exists", 409);
if (tag.name === name) {
return ApiResponse.conflict(
res,
"New tag name and old tag name are same.",
409
);
}

// Update the tag
tag.name = name || tag.name;
await tag.save();

ApiResponse.success(res, "Tag updated successfully", tag);
} catch (error) {
if (err.name === MONGOOSE_CAST_ERROR && err.kind === MONGOOSE_OBJECT_ID) {
return ApiResponse.validationError(res, "Invalid tag Fromat provided");
}
if (error.code === MONGOOSE_DUPLICATE_KEY) {
return ApiResponse.conflict(res, "Tag name already exists", 409);
}
ApiResponse.error(res, "Error while updating tag", error, 500);
}
};

// Delete a tag by ID
const deleteTag = async (req, res) => {
try {
const { id } = req.params;

const tag = await Tag.findById(id);
const tag = await Tag.findOne(req.params);
if (!tag) {
return ApiResponse.notFound(res, "Tag not found", 404);
}
Expand All @@ -96,7 +98,7 @@ const deleteTag = async (req, res) => {
module.exports = {
createTag,
getTags,
getTagById,
getATag,
updateTag,
deleteTag,
};
2 changes: 1 addition & 1 deletion controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const loginUser = asyncHandler(async (req, res) => {
}

const isPasswordValid = await user.isPasswordCorrect(password);
console.log(isPasswordValid);

if (!isPasswordValid) {
return ApiResponse.unauthorized(res, "Password didn't matched", 401);
}
Expand Down
3 changes: 3 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const { logger } = require("./middleware/logEvents.middleware");
// const errorHandler = require('./middleware/errorHandler')
const corsOptions = require("./config/corsOptions");
const mongoose = require("mongoose");
// const session = require("express-session");
// const csrf = require("lusca").csrf;
const cookieParser = require("cookie-parser");
const connectDB = require("./config/dbConn");
const restrictDirectoryAccess = require("./middleware/uploads.middleware");
Expand Down Expand Up @@ -46,6 +48,7 @@ app.use("/api/v1/user", require("./routes/user.route"));
app.use("/api/v1/role", require("./routes/roles.route"));
app.use("/api/v1/address", require("./routes/address.route"));
app.use("/api/v1/category", require("./routes/category.route"));
app.use("/api/v1/tag", require("./routes/tag.route"));

app.all("*", (req, res) => {
// res.redirect("/404.html")
Expand Down
46 changes: 46 additions & 0 deletions routes/tag.route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const router = require("express").Router();
const {
createTag,
getTags,
getATag,
deleteTag,
updateTag,
} = require("../controllers/tag.controller");
const upload = require("../middleware/multer.middleware");
const verifyJWT = require("../middleware/verifyJWT.middleware");
const verifyRoles = require("../middleware/verifyRoles.middleware");
const ROLES_LIST = require("../config/rolesList");

router
.route("/create-tag")
.post(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
createTag
);

router
.route("/get-all-tags")
.get(verifyJWT, verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER), getTags);

router
.route("/get-tag/:name")
.get(verifyJWT, verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER), getATag);

router
.route("/update-tag/:id")
.patch(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
updateTag
);

router
.route("/delete-tag/:name")
.delete(
verifyJWT,
verifyRoles(ROLES_LIST.ADMIN, ROLES_LIST.MANAGER),
deleteTag
);

module.exports = router;

0 comments on commit 9deed44

Please sign in to comment.