Files
old-naida/endpoints/addusertogroup.js
Naida Vatric 46d32196d9 Initial commit
2019-10-30 23:45:40 +01:00

61 lines
1.7 KiB
JavaScript

//Call for adding a user to a group
//
const handleAddUserToGroup = (req, res, db) => {
//Parsing req body
const { reqgroup, requser} =req.body;
//Checking if user-group combination existis in DB table groups
//if yes returns error if no inserts in DB table
db.transaction (trx => {
trx.select('groupname')
.from('groups')
.where('groupname', 'ilike', reqgroup)
.andWhere('username','ilike', requser)
.then( data => {
if (data.length===0) {
return trx('groups')
.returning('*')
.insert({
groupname: reqgroup,
username: requser
})
.into('groups')
.then( group => {
res.json(group[0]);
})
}
return res.status(400).json('This user already exists in this group.');
})
.then(trx.commit)
.catch(trx.rollback)
.catch (err => res.status(400).json('Error accesing database.'))
})
//Checking if user existis in DB table users
//if no inserts new user (implicitly)
db.transaction (trx => {
trx.select('username')
.from('users')
.where('username', 'ilike', requser)
.then ( data => {
if (data.length===0) {
return trx('users')
.returning('*')
.insert( {
username: requser
})
.then(user => {
console.log('Inserted new user implicitly.');
})
}
})
.then(trx.commit)
.catch(trx.rollback)
})
}
module.exports = {
handleAddUserToGroup
}