51 lines
1.3 KiB
JavaScript
51 lines
1.3 KiB
JavaScript
const Role = require('./roleModel')
|
|
const AppError = require('../../globalErrorHandler/AppError')
|
|
|
|
module.exports.getAllRoles = async (query = {}) => {
|
|
const mongoQuery = {}
|
|
const search = (query.search || query.query || '').trim()
|
|
if (search) {
|
|
mongoQuery.$or = [
|
|
{ nativeName: { $regex: search, $options: 'i' } },
|
|
{ englishName: { $regex: search, $options: 'i' } },
|
|
]
|
|
}
|
|
return Role.find(mongoQuery).populate('permissions').sort({ createdAt: -1 })
|
|
}
|
|
|
|
|
|
module.exports.createRole = async (data) => {
|
|
const role = await Role.create(data)
|
|
return Role.findById(role._id).populate('permissions')
|
|
}
|
|
|
|
module.exports.getRole = async (roleId) => {
|
|
const role = await Role.findById(roleId).populate('permissions')
|
|
|
|
if (!role) {
|
|
throw new AppError('NoRoleFound', 404, {})
|
|
}
|
|
|
|
return role
|
|
}
|
|
|
|
module.exports.updateRole = async (roleId, data) => {
|
|
const role = await Role.findOneAndUpdate({ _id: roleId }, data, { new: true }).populate('permissions')
|
|
|
|
if (!role) {
|
|
throw new AppError('NoRoleFound', 404, {})
|
|
}
|
|
|
|
return role
|
|
}
|
|
|
|
module.exports.deleteRole = async (roleId) => {
|
|
const role = await Role.findByIdAndUpdate(roleId, { isActive: false }, { new: true })
|
|
|
|
if (!role) {
|
|
throw new AppError('NoRoleFound', 404, {})
|
|
}
|
|
|
|
return null
|
|
}
|