Skip to content

Commit

Permalink
feat: create get single product endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
riyoneri committed Nov 11, 2024
1 parent 0381545 commit 0249617
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
31 changes: 31 additions & 0 deletions src/controllers/admin/products.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,34 @@ export const getAllProducts = async (
next(error);
}
};

export const getSingleProduct = async (
request: Request,
response: Response,
next: NextFunction,
) => {
try {
const validationErrors = getValidationResult(request);

if (validationErrors) {
const error = new CustomError(
ValidationErrorMessage,
400,
validationErrors,
);
return next(error);
}

const product = await Product.findOne({ _id: request.params.productId });

if (!product)
return response
.status(404)
.json({ message: getNotFoundMessage("Product") });

response.status(200).json(product.toObject());
} catch {
const error = new CustomError(ServerErrorMessage);
next(error);
}
};
8 changes: 7 additions & 1 deletion src/routes/admin.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
deleteCategoryChain,
getAllSanitizer,
getSingleCategoryChain,
getSingleProductChain,
updateCategoryChain,
} from "../validations";

Expand Down Expand Up @@ -68,6 +69,11 @@ router
createProductChain(),
productsController.createProduct,
)
.get("/products", getAllSanitizer(), productsController.getAllProducts);
.get("/products", getAllSanitizer(), productsController.getAllProducts)
.get(
"/products/:productId",
getSingleProductChain(),
productsController.getSingleProduct,
);

export default router;
9 changes: 8 additions & 1 deletion src/validations/admin-products.validation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { body } from "express-validator";
import { body, param } from "express-validator";

export const createProductChain = () => [
body("name", "Name is required")
Expand Down Expand Up @@ -33,3 +33,10 @@ export const createProductChain = () => [
.isMongoId()
.withMessage("Category ID must be valid."),
];

export const getSingleProductChain = () =>
param("productId", "Invalid product id")
.isString()
.trim()
.notEmpty({ ignore_whitespace: true })
.isMongoId();

0 comments on commit 0249617

Please sign in to comment.