changes to grant creation and model clean

This commit is contained in:
Arjun Patel
2019-01-30 11:46:14 -08:00
parent 7b19e69447
commit 556369af11
4 changed files with 30 additions and 29 deletions
+28 -19
View File
@@ -1,35 +1,44 @@
const db = require('../../config/db.config.js'),
errorMaker = require('../../helpers/error.maker');
const { Grant, Cause, Region, Organization } = db;
const { Grant, Cause, Region, Organization, sequelize } = db;
// Create a grant for certain donor
exports.create = (req, res, next) => {
const donor_id = req.params.donor_id;
const donor_id = req.user.id;
const { name, amount, monthly, causes, regions, organizations } = req.body;
Grant.create({
donor_id,
name,
amount,
monthly,
num_causes: causes.length,
num_regions: regions.length
})
.then(grant => {
return Promise.all([
grant.addCauses(causes),
grant.addRegions(regions),
grant.addOrganizations(organizations)
]).then(result => result);
return sequelize
.transaction(function(t) {
return Grant.create(
{
donor_id,
name,
amount,
monthly,
num_causes: causes.length,
num_regions: regions.length
},
{ transaction: t }
).then(grant => {
return Promise.all([
grant.addCauses(causes, { transaction: t }),
grant.addRegions(regions, { transaction: t }),
grant.addOrganizations(organizations, { transaction: t })
]).then(result => grant);
});
})
.then(result => {
.then(function(grant) {
// transaction committed
res.status(201).json({
result,
grant,
message: 'Grant Created'
});
})
.catch(error => next(error));
.catch(function(error) {
// transaction rollback
next(error);
});
};
// Find grants with causes, regions, and organizations by donor_id
@@ -20,7 +20,7 @@ exports.findSuggested = (req, res, next) => {
const QUERY =
'SELECT * from organizations ' +
'WHERE primary_cause IN (:causes) and primary_region IN (:regions) ' +
'WHERE primary_cause IN (:causes) or primary_region IN (:regions) ' +
'LIMIT :max_orgs';
db.sequelize
.query(QUERY, {
-4
View File
@@ -14,10 +14,6 @@ module.exports = (sequelize, DataTypes) => {
type: DataTypes.INTEGER,
allowNull: false
},
last_payment: {
type: DataTypes.DATE,
default: new Date()
},
monthly: {
type: DataTypes.BOOLEAN,
allowNull: false,
+1 -5
View File
@@ -20,11 +20,7 @@ router.get('/grants/', checkAuth(roles.DONOR), controllers.grant.findByDonorId);
* - monthly true or false
* - donor_id
* */
router.post(
'/grants/:donor_id',
checkAuth(roles.DONOR),
controllers.grant.create
);
router.post('/grants/', checkAuth(roles.DONOR), controllers.grant.create);
// DELECT a grant of a donor
router.delete(