Initial commit
This commit is contained in:
60
endpoints/addusertogroup.js
Normal file
60
endpoints/addusertogroup.js
Normal file
@@ -0,0 +1,60 @@
|
||||
//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
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user