Skip to content

Commit

Permalink
Refactored product module server code
Browse files Browse the repository at this point in the history
  • Loading branch information
foyzulkarim committed Mar 29, 2022
1 parent 9e0c37f commit 62272ef
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 161 deletions.
110 changes: 14 additions & 96 deletions server/src/modules/product/controller.js
Original file line number Diff line number Diff line change
@@ -1,114 +1,32 @@
/* eslint-disable no-undef */
const express = require("express");
const { getQuery } = require("./service");
const {
save,
update,
deleteById,
getById,
search,
count,
} = require("./service");
getByIdHandler,
saveHandler,
updateHandler,
searchHandler: baseSearchHandler,
countHandler: baseCountHandler,
deleteHandler,
} = require("../../core/controller");
const { validate } = require("./request");
const { handleValidation } = require("../../common/middlewares");
const { NotFound } = require("../../common/errors");

const router = express.Router();
const ModelName = "Product";

const getHandler = async (req, res, next) => {
try {
const items = [
{ id: 1, name: "Product 1" },
{ id: 2, name: "Product 2" },
];
const result = {
data: items,
total: items.length,
success: true,
};
return res.status(200).send(result);
} catch (error) {
return next(error, req, res);
}
};

const getByIdHandler = async (req, res, next) => {
try {
const { id } = req.query;
const item = await getById(id, ModelName);
if (item) {
return res.status(200).send(item);
}
throw new NotFound(`Product not found by the id: ${id}`);
} catch (error) {
return next(error, req, res);
}
};

const postHandler = async (req, res, next) => {
try {
const { body } = req;
const id = await save(body, ModelName);
return res.status(201).send(id);
} catch (error) {
return next(error, req, res);
}
};

const searchHandler = async (req, res, next) => {
try {
if (!req.body.pageSize) {
req.body.pageSize = 10;
}
if (!req.body.current) {
req.body.current = 1;
}
const result = await search(req.body);
const response = { success: true, ...result };
return res.status(200).send(response);
// const response = { success: false, errorMessage: 'Super duper error handling mechanism', ...result };
// res.status(400).send(response);
} catch (error) {
return next(error, req, res);
}
req.searchQuery = getQuery(req.body);
return baseSearchHandler(req, res, next);
};

const countHandler = async (req, res, next) => {
try {
const result = await count(req.body);
const response = { success: true, ...result };
return res.status(200).send(response);
} catch (error) {
return next(error, req, res);
}
};

const putHandler = async (req, res, next) => {
try {
const { body } = req;
const id = await update(body, ModelName);
return res.status(200).send(id);
} catch (error) {
return next(error, req, res);
}
};

const deleteHandler = async (req, res, next) => {
try {
const { id } = req.query;
await deleteById(id, ModelName);
return res
.status(200)
.send({ success: true, message: `${ModelName} deleted` });
} catch (error) {
return next(error, req, res);
}
req.searchQuery = getQuery(req.body);
return baseCountHandler(req, res, next);
};

router.get("/", getHandler);
router.get("/detail", getByIdHandler);
router.post("/create", handleValidation(validate), postHandler);
router.put("/update", handleValidation(validate), putHandler);
router.post("/create", handleValidation(validate), saveHandler);
router.put("/update", handleValidation(validate), updateHandler);
router.post("/search", searchHandler);
router.post("/count", countHandler);
router.delete("/delete", deleteHandler);
Expand Down
14 changes: 13 additions & 1 deletion server/src/modules/product/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,21 @@ const {
authenticateRequest,
authorizeRequest,
} = require("../../common/middlewares");
const { name: ModelName } = require("./model");

const processRequest = async (req, res, next) => {
req.modelName = ModelName;
return next();
};

const init = async (app) => {
app.use("/api/products", authenticateRequest, authorizeRequest, routes);
app.use(
"/api/products",
authenticateRequest,
authorizeRequest,
processRequest,
routes
);
return app;
};

Expand Down
6 changes: 5 additions & 1 deletion server/src/modules/product/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,8 @@ schema.index({ cost: 1 });
// reference model
const Product = mongoose.model("Product", schema);

module.exports = Product;
const ModelName = "Product";
// reference model
// const Role = mongoose.model("Role", schema);

module.exports = { Model: Product, name: ModelName };
70 changes: 7 additions & 63 deletions server/src/modules/product/service.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
// load repository.js
const { save, update, getById, deleteById } = require("../../core/repository");
const Model = require("./model");
const { name: ModelName } = require("./model");

// const eventEmitter = require("../../core/event-manager").getInstance();
// const modelName = "Product";

const search = async (payload) => {
const getQuery = (payload) => {
const queries = [];

if (payload.name) {
Expand Down Expand Up @@ -33,62 +29,7 @@ const search = async (payload) => {
if (queries.length > 1) {
query = { $and: queries };
}
const take = parseInt(payload.pageSize, 10);
const skip = (parseInt(payload.current, 10) - 1) * take;

// sort
let sort = {};
if (payload.sort) {
const key = payload.sort;
const value = parseInt(payload.order, 10) ?? 1;
sort[key] = value;
} else {
sort = { updatedAt: -1 };
}

const data = await Model.collection
.find(query)
.sort(sort)
.skip(skip)
.limit(take);
const items = { data: await data.toArray(), total: 200 };
return items;
};

const count = async (payload) => {
// let searchQuery = null;
const queries = [];

if (payload.name) {
queries.push({ name: { $regex: payload.name, $options: "i" } });
}

// product.size (number)
if (payload.size) {
queries.push({ size: parseInt(payload.size, 10) });
}

// payload.fromDate && payload.toDate
if (payload.fromDate && payload.toDate) {
queries.push({
createdAt: {
$gte: new Date(payload.fromDate),
$lte: new Date(payload.toDate),
},
});
}

let query = {};
if (queries.length === 1) {
query = { ...queries[0] };
}
if (queries.length > 1) {
query = { $and: queries };
}

const t = await Model.collection.find(query).count();
const items = { total: t };
return items;
return query;
};

const setupEventListeners = () => {
Expand All @@ -105,4 +46,7 @@ const setupEventListeners = () => {

setupEventListeners();

module.exports = { save, update, deleteById, getById, search, count };
module.exports = {
getQuery,
modelName: ModelName,
};

0 comments on commit 62272ef

Please sign in to comment.