Skip to content

Commit

Permalink
Refactor profile module.
Browse files Browse the repository at this point in the history
  • Loading branch information
HranikBs23 committed Feb 23, 2022
1 parent 4e8b1a8 commit 4883cf7
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 115 deletions.
19 changes: 4 additions & 15 deletions src/modules/platform/permission/permission.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const ProfilePermission = require(path.join(process.cwd(), 'src/modules/platform
const RolePermission = require(path.join(process.cwd(), 'src/modules/platform/permission/role-permission.model'));
const { makeCustomSlug } = require(path.join(process.cwd(), 'src/modules/core/services/slug'));
const PermissionService = require(path.join(process.cwd(), 'src/modules/platform/permission/permission-service.model'));
const { Op } = require('sequelize');


async function getPermissions(req, res) {
Expand Down Expand Up @@ -81,7 +82,7 @@ async function getPermissions(req, res) {
]
});

const totalPermissions = Permission.count();
const totalPermissions = await Permission.count();

const data = {
permissions,
Expand Down Expand Up @@ -194,16 +195,7 @@ async function updatePermission(req, res) {
try {
const { title, type, description, services } = req.body;

const permission = await Permission.findOne({
where: { id: req.params.id },
include: [
{
model: PermissionService,
as: "permission_services"
}
]
});

const permission = await Permission.findOne({ where: { id: req.params.id }});
if (!permission) return res.status(404).send('Permission not found!');

if (title) {
Expand All @@ -216,10 +208,7 @@ async function updatePermission(req, res) {
if (description) await permission.update({ description });

if (services) {

permission.permission_services.forEach( async () => {
await PermissionService.destroy({ where: { permission_id: permission.id }})
});
await PermissionService.destroy({ where: { permission_id: permission.id }});

services.forEach(async serviceId => {
const service = await Service.findOne({ where: { id: serviceId }});
Expand Down
196 changes: 97 additions & 99 deletions src/modules/platform/profile/profile.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,55 @@ const Profile = require('./profile.model');
const Permission = require(path.join(process.cwd(), 'src/modules/platform/permission/permission.model'));
const ProfilePermission = require(path.join(process.cwd(), 'src/modules/platform/permission/profile-permission.model'));
const { makeCustomSlug } = require(path.join(process.cwd(), 'src/modules/core/services/slug'));
const { Op } = require('sequelize');

async function getProfiles(req, res) {
try {
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 = [
"title",
"slug",
"type",
"description",
"created_at"
];

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

if (orderBy === "created_by") {
order.splice(0, 0, [
{ model: User, as: "createdByUser" },
"first_name",
orderType
]);
order.splice(1, 0, [
{ model: User, as: "createdByUser" },
"last_name",
orderType
]);
}

// const filterOptions = { id: { [Op.ne]: req.user.id } };

const profiles = await Profile.findAll({
offset,
limit,
order,
include: [
{
model: ProfilePermission,
Expand All @@ -23,7 +68,20 @@ async function getProfiles(req, res) {
]
});

res.status(200).send(profiles);
const totalProfiles = await Profile.count();

const data = {
profiles,
metaData: {
page: page + 1,
limit: limit,
total: totalProfiles,
start: limit * page + 1,
end: offset + limit > totalProfiles ? totalProfiles : offset + limit,
}
}

res.status(200).send(data);
}
catch (err) {
console.error(err);
Expand All @@ -33,11 +91,9 @@ async function getProfiles(req, res) {

async function getProfile(req, res) {
try {
const { id } = req.params;

const profile = await Profile.findOne({
where: {
id
id: req.params.id
},
include: [
{
Expand Down Expand Up @@ -68,43 +124,32 @@ async function getProfile(req, res) {
async function createProfile(req, res) {
try {
const { title, type, description, permissions } = req.body;
const userId = req.user.id;

permissions.forEach(async permissionId => {
const permissionExist = await Permission.findOne({
where: {
id: permissionId
}
});

if (!permissionExist) return res.status(400).send('Bad request.');
});

const slug = makeCustomSlug(title);

const existProfile = await Profile.findOne({
where: {
slug
const [profile, created] = await Profile.findOrCreate({
where: { slug },
defaults: {
title,
slug,
type,
description,
created_by: req.user.id,
updated_by: req.user.id
}
});

if (existProfile) return res.status(400).send('Profile already exists!');
if (!created) return res.status(400).send('Profile already exists!');

const profile = await Profile.create({
title,
slug,
type,
description,
created_by: userId,
updated_by: userId
});
permissions.forEach(async permissionId => {
const permission = await Permission.findOne({ where: { id: permissionId }});

permissions.forEach(async element =>
await ProfilePermission.create({
permission_id: element,
profile_id: profile.id
})
);
if(permission) {
await ProfilePermission.create({
permission_id: permission.id,
profile_id: profile.id
});
}
});

res.status(201).send(profile);
}
Expand All @@ -116,57 +161,33 @@ async function createProfile(req, res) {

async function updateProfile(req, res) {
try {
const { id } = req.params;
const { title, type, description, permissions } = req.body;
const userId = req.user.id;

const profile = await Profile.findOne({
where: {
id
},
include: [
{
model: ProfilePermission,
as: "profile_permissions"
}
]
});

const profile = await Profile.findOne({ where: { id: req.params.id }});
if (!profile) return res.status(404).send('Profile not found!');

if (title) {
const slug = makeCustomSlug(title);
await profile.update({ title, slug, updated_by: userId });
await profile.update({ title, slug, updated_by: req.user.id });
}

if (type) await profile.update({ type, updated_by: userId });
if (description) await profile.update({ description, updated_by: userId });
if (type) await profile.update({ type, updated_by: req.user.id });

if (description) await profile.update({ description, updated_by: req.user.id });

if (permissions) {
permissions.forEach(async permissionId => {
const permissionExist = await Permission.findOne({
where: {
id: permissionId
}
});
await ProfilePermission.destroy({ where: { profile_id: profile.id }});

if (!permissionExist) return res.status(400).send('Bad request.');
});
permissions.forEach(async permissionId => {
const permission = await Permission.findOne({ where: { id: permissionId }});

profile.profile_permissions.forEach(async element =>
await ProfilePermission.destroy({
where: {
if (permission) {
await ProfilePermission.create({
permission_id: permission.id,
profile_id: profile.id
}
})
);

permissions.forEach(async permissionId =>
await ProfilePermission.create({
permission_id: permissionId,
profile_id: profile.id
})
);
});
}
});
}

res.status(201).send(profile);
Expand All @@ -179,39 +200,16 @@ async function updateProfile(req, res) {

async function deleteProfile(req, res) {
try {
const { id } = req.params;

const profile = await Profile.findOne({
where: {
id
},
include: [
{
model: ProfilePermission,
as: "profile_permissions",
attributes: ["id"],
include: [
{
model: Permission,
as: "permission",
attributes: ["id", "title", "slug"]
}
]
}
]
id: req.params.id,
type: { [Op.ne]: 'standard' }
}
});

if (!profile) return res.status(404).send('Profile not found!');
if (profile.type == 'standard') return res.status(400).send("You can't delete default profile.");

profile.profile_permissions.forEach(async element =>
await ProfilePermission.destroy({
where: {
profile_id: profile.id
}
})
);

await ProfilePermission.destroy({ where: { profile_id: profile.id }});
await profile.destroy();

res.status(200).send(profile);
Expand Down
1 change: 0 additions & 1 deletion src/modules/platform/profile/profile.model.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const path = require('path');
const sequelize = require(path.join(process.cwd(), 'src/config/lib/sequelize'));
const ProfilePermission = require(path.join(process.cwd(), 'src/modules/platform/permission/profile-permission.model'));
const Permission = require(path.join(process.cwd(), 'src/modules/platform/permission/permission.model'));
const { DataTypes } = require('sequelize');

const Profile = sequelize.define('profiles', {
Expand Down
3 changes: 3 additions & 0 deletions src/modules/platform/user/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ 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.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' });

Expand Down

0 comments on commit 4883cf7

Please sign in to comment.