/var/www/greso.tech/server/nsm/controllers/branch
Edit: /var/www/greso.tech/server/nsm/controllers/branch/add_user.js (1557B)
module.exports = function ({ db, logger }) {
const { NotFound, BadRequest } = require('../../responseModels/errors')
const { isSet, isEmail, isPhone, isEmpty, minLength, isNumber } = require('../../utils/validator.util')
return async (req, res, next) => {
logger.child({ path: req.path, request: req.body }).info()
let t1 = performance.now()
let transaction = await db.sequelize.transaction()
try {
const { branchId, userId, roleId } = req.body
if (
!isSet(branchId) ||
!isSet(userId) ||
isEmpty(branchId) ||
isEmpty(userId) ||
isEmpty(roleId)
) {
throw new BadRequest({ lang: req.user?.languageCode })
}
const branch = await db.branch.findOne({ where: { id: branchId } })
const user = await db.user.findOne({ where: { id: userId } })
const role = await db.role.findOne({ where: { id: roleId } })
if (!user || !branch || !role) {
throw new NotFound({ lang: req.user?.languageCode })
}
let userBranch = await db.branchUsers.findOne({
where: { userId: user.id, branchId: branch.id }
})
if (userBranch) {
// пользователь существует
// обновить роль
userBranch.roleId = role.id
await userBranch.save()
} else {
await db.branchUsers.create({
userId: user.id,
branchId: branch.id,
roleId: role.id
})
}
await transaction.commit()
const time = performance.now() - t1
return res.status(200).json({ status: 'success', time })
} catch (err) {
transaction?.rollback()
next(err)
}
}
}