Skip to content

Commit

Permalink
Remove issue of circular dependency in sequelize.
Browse files Browse the repository at this point in the history
  • Loading branch information
HranikBs23 committed Feb 26, 2022
1 parent 40c07fc commit 2047d6a
Show file tree
Hide file tree
Showing 9 changed files with 97 additions and 59 deletions.
3 changes: 2 additions & 1 deletion seeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ async function init() {
require(path.join(process.cwd(), 'src/modules/order/order-product.model'));
require(path.join(process.cwd(), 'src/modules/order/order.model'));
require(path.join(process.cwd(), 'src/modules/cart/cart.model'));
require(path.join(process.cwd(), 'src/modules/review/review.model'));
require(path.join(process.cwd(), 'src/modules/review/product-review.model'));
require(path.join(process.cwd(), 'src/modules/review/shop-review.model'));

await sequelize.sync();

Expand Down
3 changes: 3 additions & 0 deletions src/modules/category/category.model.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const path = require("path");
const sequelize = require(path.join(process.cwd(), 'src/config/lib/sequelize'));
const Product = require(path.join(process.cwd(), 'src/modules/product/product.model'));
const { DataTypes } = require('sequelize');
const SubCategory = require('./sub-category.model');

Expand All @@ -24,4 +25,6 @@ const Category = sequelize.define('categories', {
Category.hasMany(SubCategory, { as: 'subCategories', foreignKey: 'category_id' });
SubCategory.belongsTo(Category, { as: 'category', foreignKey: 'category_id' });

Product.belongsTo(Category, { as: 'category', foreignKey: 'category_id' });

module.exports = Category;
49 changes: 24 additions & 25 deletions src/modules/platform/user/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const path = require("path");
const Review = require("../../review/review.model");
const review = require("./review.model");
const User = require("./user.model");
const Profile = require(path.join(process.cwd(), "src/modules/platform/profile/profile.model"));
const Role = require(path.join(process.cwd(), "src/modules/platform/role/role.model"));
const ProfilePermission = require(path.join(process.cwd(), "src/modules/platform/permission/profile-permission.model"));
Expand Down Expand Up @@ -204,8 +203,8 @@ async function getUsers(req, res) {
order,
include: [
{
model: Review,
as: "review",
model: Profile,
as: "profile",
},
{
model: Role,
Expand Down Expand Up @@ -246,7 +245,7 @@ async function getUser(req, res) {
try {
const { id } = req.params;

const review = await review.findOne({
const user = await User.findOne({
where: {
id,
},
Expand Down Expand Up @@ -318,9 +317,9 @@ async function getUser(req, res) {
],
});

if (!review) return res.status(404).send("Review not found!");
if (!user) return res.status(404).send("User not found!");

res.status(200).send(review);
res.status(200).send(user);
} catch (err) {
console.error(err);
res.status(500).send("Internal server error!");
Expand All @@ -331,18 +330,18 @@ async function createUser(req, res) {
try {
const { first_name, last_name, email, password, profile_id, role_id } = req.body;

const existReview = await Review.findOne({
const existUser = await User.findOne({
where: {
email,
},
});

if (existReview)
if (existUser)
return res
.status(400)
.send("Already registered with this email address.");

const review = await Review.findOne({
const profile = await Profile.findOne({
where: {
id: profile_id,
},
Expand All @@ -356,7 +355,7 @@ async function createUser(req, res) {
},
});

const review = await review.create({
const user = await User.create({
first_name,
last_name,
email,
Expand All @@ -368,8 +367,8 @@ async function createUser(req, res) {
});


const { password: Password, ...restreviewInfo } = review.dataValues;
res.status(201).send(restreviewInfo);
const { password: Password, ...restUserInfo } = user.dataValues;
res.status(201).send(restUserInfo);
} catch (err) {
console.log(err);
res.status(500).send("Internal server error!");
Expand All @@ -381,23 +380,23 @@ async function updateUser(req, res) {
const { id } = req.params;
const { first_name, last_name, email, profile_id, role_id } = req.body;

const review = await review.findOne({
const user = await User.findOne({
where: {
id,
},
});

if (!review) return res.status(404).send("review not found!");
if (!user) return res.status(404).send("User not found!");

if (first_name) user.update({ first_name, updated_by: req.user.id });
if (last_name) user.update({ last_name, updated_by: req.user.id });
if (email) {
const existingreview = await review.findOne({
const existingUser = await User.findOne({
where: {
email: email,
}
});
if (existingreview) return res.status(400).send("Already registered with this email address.");
if (existingUser) return res.status(400).send("Already registered with this email address.");

user.update({ email, updated_by: req.user.id });
}
Expand Down Expand Up @@ -427,8 +426,8 @@ async function updateUser(req, res) {
}

{
const { password, password_updated_at, ...reviewInfo } = review.dataValues;
res.status(201).send(reviewInfo);
const { password, password_updated_at, ...userInfo } = user.dataValues;
res.status(201).send(userInfo);
}

} catch (err) {
Expand All @@ -441,19 +440,19 @@ async function deleteUser(req, res) {
try {
const { id } = req.params;

const review = await review.findOne({
const user = await User.findOne({
where: {
id,
},
});

if (!review) return res.status(404).send("review not found!");
if (!user) return res.status(404).send("User not found!");

await review.destroy();
await user.destroy();

{
const { password, password_updated_at, ...reviewInfo } = review.dataValues;
res.status(201).send(reviewInfo);
const { password, password_updated_at, ...userInfo } = user.dataValues;
res.status(201).send(userInfo);
}
} catch (err) {
console.log(err);
Expand All @@ -469,4 +468,4 @@ module.exports.createUser = createUser;
module.exports.updateUser = updateUser;
module.exports.deleteUser = deleteUser;
module.exports.getSignedInUserProfile = getSignedInUserProfile;
module.exports.updateSignedInUserProfile = updateSignedInUserProfile;
module.exports.updateSignedInUserProfile = updateSignedInUserProfile;
8 changes: 4 additions & 4 deletions src/modules/platform/user/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,14 @@ User.prototype.validPassword = function (password) {
User.belongsTo(User, { as: 'createdByUser', foreignKey: 'created_by' });
User.belongsTo(User, { as: 'updatedByUser', foreignKey: 'created_by' });

Profile.hasMany(User, { as: 'users', foreignKey: 'profile_id' });
User.belongsTo(Profile, { as: 'profile', foreignKey: 'profile_id' });
Profile.hasMany(User, { as: 'users', foreignKey: 'profile_id', constraints: false });
User.belongsTo(Profile, { as: 'profile', foreignKey: 'profile_id', constraints: false });

Profile.belongsTo(User, { as: "createdByUser", foreignKey: "created_by" });
Profile.belongsTo(User, { as: "updatedByUser", foreignKey: "updated_by" });

Role.hasMany(User, { as: 'users', foreignKey: 'role_id' });
User.belongsTo(Role, { as: 'role', foreignKey: 'role_id' });
Role.hasMany(User, { as: 'users', foreignKey: 'role_id', constraints: false });
User.belongsTo(Role, { as: 'role', foreignKey: 'role_id', constraints: false });

Role.belongsTo(User, { as: "createdByUser", foreignKey: "created_by" });
Role.belongsTo(User, { as: "updatedByUser", foreignKey: "updated_by" });
Expand Down
8 changes: 2 additions & 6 deletions src/modules/product/product.controller.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
const path = require("path");
const Shop = require("../shop/shop.model");
const Product = require("./product.model");
const Category = require("./category.model");

const { getPagination, getPagingData } = require("./services/product.service");

const Product = require(path.join(process.cwd(), "src/modules/product/product.model"));
const Shop = require(path.join(process.cwd(), "src/modules/shop/shop.model"));

async function getProducts(req, res) {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/modules/review/product-review.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ const ProductReview = sequelize.define("product_reviews", {

ProductReview.belongsTo(Product, { as: 'product', foreignKey: 'product_id' });

module.exports = Review;
module.exports = ProductReview;
1 change: 1 addition & 0 deletions src/modules/review/review.controller.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const path = require("path");
const ProductReview = require(path.join(process.cwd(), "src/modules/review/product-review.model"));
const ShopReview = require(path.join(process.cwd(), "src/modules/review/shop-review.model"));
const Product = require(path.join(process.cwd(), "src/modules/product/product.model"));
Expand Down
2 changes: 1 addition & 1 deletion src/modules/review/shop-review.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ const ShopReview = sequelize.define("shop_reviews", {

ShopReview.belongsTo(Shop, { as: 'shop', foreignKey: 'shop_id' });

module.exports = Review;
module.exports = ShopReview;
80 changes: 59 additions & 21 deletions src/modules/shop/shop.controllers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const path = require("path");
const Category = require(path.join(process.cwd(), "src/modules/category/category.model"));
const Product = require(path.join(process.cwd(), 'src/modules/product/product.model'));
// const Order = require(path.join(process.cwd(), 'src/modules/order/order.model'));
const { generateAccessToken } = require('./services/shop.service');
Expand Down Expand Up @@ -135,41 +136,78 @@ async function updateProduct(req, res) {

async function getProducts(req, res) {
try {
const page = +req.query.page || 1;
const limit = +req.query.limit || 15;
const offset = (page - 1) * limit;
let { orderBy, orderType } = req.query;
orderType = orderType || 'asc';
let order = [['created_at', 'desc']];
const page = req.query.page ? req.query.page - 1 : 0;
if (page < 0) return res.status(404).send("page must be greater or equal 1");

const limit = req.query.limit ? +req.query.limit : 15;
const offset = page * limit;

const orderBy = req.query.orderBy ? req.query.orderBy : null;
const orderType = req.query.orderType === "asc" || req.query.orderType === "desc" ? req.query.orderType : "asc";

const order = [
["created_at", "DESC"],
["id", "DESC"]
];

const sortableColumns = [
"name",
"price",
"description",
"discount",
"stock_quantity",
"created_at"
];

if (orderBy && sortableColumns.includes(orderBy)) {
order.splice(0, 0, [orderBy, orderType]);
}

if (orderBy) {
order.push([orderBy, orderType]);
if (orderBy === "shop") {
order.splice(0, 0, [
{ model: Shop, as: "shop" },
"name",
orderType
]);
}

if (orderBy === "category") {
order.splice(0, 0, [
{ model: Category, as: "category" },
"name",
orderType
]);
}

const filterOptions = { shop_id: req.user.id };

const products = await Product.findAll({
where: {
shop_id: req.user.id
},
where: filterOptions,
offset,
limit,
order,
include: [
{
model: Shop,
as: 'shop'
},
{
model: Category,
as: 'category'
}
],
offset,
limit,
order
]
});

const total = await Product.count();
const totalProducts = await Product.count();

const data = {
products,
meta: {
start: offset + 1,
end: Math.min(total, page * limit),
total,
page
metaData: {
page: page + 1,
limit: limit,
total: totalProducts,
start: limit * page + 1,
end: offset + limit > totalProducts ? totalProducts : offset + limit,
}
};

Expand Down

0 comments on commit 2047d6a

Please sign in to comment.