Spaces:
Runtime error
Runtime error
import { Request, Response } from 'express'; | |
import Role from '../models/roles'; | |
import { FindOptions, Op } from 'sequelize'; | |
import { logger } from '../utils/logger'; | |
import Permission from '../models/permissions'; | |
import RolePermission from '../models/rolePermissions'; | |
const buildRoleWhereClause = (filter: Record<string, any>) => { | |
const whereClause: any = {}; | |
if (filter) { | |
if (filter.name) { | |
whereClause.name = { [Op.like]: `%${filter.name}%` }; | |
} | |
if (filter.date) { | |
const date = new Date(filter.date); | |
if (!isNaN(date.getTime())) { | |
const startOfDay = new Date(date); | |
startOfDay.setHours(0, 0, 0, 0); | |
const endOfDay = new Date(date); | |
endOfDay.setHours(23, 59, 59, 999); | |
whereClause.created_at = { | |
[Op.gte]: startOfDay, | |
[Op.lte]: endOfDay | |
}; | |
} | |
} | |
if (filter.created_before) { | |
const beforeDate = new Date(filter.created_before); | |
if (!isNaN(beforeDate.getTime())) { | |
whereClause.created_at = { ...whereClause.created_at, [Op.lte]: beforeDate }; | |
} | |
} | |
if (filter.created_after) { | |
const afterDate = new Date(filter.created_after); | |
if (!isNaN(afterDate.getTime())) { | |
whereClause.created_at = { ...whereClause.created_at, [Op.gte]: afterDate }; | |
} | |
} | |
} | |
return whereClause; | |
} | |
const getAllRoles = async (req: Request, res: Response) => { | |
try { | |
const { sort_by, sort_order, page, limit } = req.query; | |
const filter = req.query.filter as Record<string, any>; | |
const allowedSortColumns = ['id', 'name', 'created_at']; | |
const whereClause = buildRoleWhereClause(filter); | |
const currentPage = parseInt(page as string) || 1; | |
const pageSize = parseInt(limit as string) || 10; | |
const options: FindOptions = { | |
where: whereClause, | |
limit: pageSize, | |
offset: (currentPage - 1) * pageSize, | |
order: [] | |
}; | |
if (sort_by && allowedSortColumns.includes(sort_by as string)) { | |
options.order = [[sort_by as string, sort_order === 'desc' ? 'DESC' : 'ASC']]; | |
} else { | |
options.order = [['id', 'ASC']]; | |
} | |
const [roles, totalRoles] = await Promise.all([ | |
Role.findAll(options), | |
Role.count({ where: whereClause }), | |
]); | |
const data = { | |
page: currentPage, | |
limit: pageSize, | |
total: totalRoles, | |
data: roles | |
} | |
res.status(200).json(data); | |
} catch (error) { | |
logger.error('Error fetching roles:'); | |
logger.error(error); | |
res.status(500).json({ error: 'Error fetching roles' }); | |
} | |
} | |
const assignPermissionsToRole = async (req: Request, res: Response) => { | |
try { | |
const { roleId } = req.params; | |
const { permission_ids } = req.body; | |
// Validate if the role exists | |
const role = await Role.findByPk(roleId); | |
if (!role) { | |
return res.status(404).json({ error: 'Role not found' }); | |
} | |
// Fetch all permissions that match the given IDs | |
const existingPermissions = await Permission.findAll({ where: { id: permission_ids } }); | |
// Extract IDs of existing permissions | |
const existingPermissionIds = existingPermissions.map(permission => permission.id); | |
// Identify non-existent permissions | |
const nonExistentPermissionIds = permission_ids.filter((id: number) => !existingPermissionIds.includes(id)); | |
// Assign only the existing permissions to the role | |
const rolePermissions = await Promise.all( | |
existingPermissionIds.map(async (permission_id: number) => { | |
return await RolePermission.create({ role_id: parseInt(roleId, 10), permission_id }); | |
}) | |
); | |
return res.status(201).json({ | |
message: 'Permissions processed successfully', | |
assignedPermissions: rolePermissions, | |
nonExistentPermissions: nonExistentPermissionIds, | |
}); | |
} catch (error) { | |
logger.error('Error assigning permissions to role:'); | |
logger.error(error); | |
return res.status(500).json({ | |
error: 'Error while assigning permissions to the role.', | |
}); | |
} | |
}; | |
export { getAllRoles,assignPermissionsToRole } |