Skip to content

Instantly share code, notes, and snippets.

@ayoola-solomon
Last active November 13, 2015 15:23
Show Gist options
  • Save ayoola-solomon/5dac781e032661d9108f to your computer and use it in GitHub Desktop.
Save ayoola-solomon/5dac781e032661d9108f to your computer and use it in GitHub Desktop.
Refactor function
var peers = function(req, res) {
try {
findPeers(req.params.id, function(err, data) {
if (data) {
res.status(200).json(data);
}
else {
res.status(404).json({
message: 'Fellows does not exist'
});
}
});
}
catch(err) {
logger.error(err);
res.status(500).json(err);
}
}
var findPeers = function(fellowId, cb) {
var peers = [];
models.Fellow
.findById(fellowId)
.then(function(fellow) {
if (fellow) {
switch (fellow.level) {
case 'D0A - MONTH ONE':
case 'D0B - SIMULATIONS':
case 'D0C - SIMULATIONS':
fetchTeamAndCohortPeers(fellow, peers, function(err, data) {
if (data) {
cb(err, data);
}
});
break;
case 'D1 Jr Consultant':
case 'D2 Consultant':
case 'D3 Consultant':
case 'D4 Consultant':
fetchAllPeers(fellow, peers, function(err, data) {
if (data) {
cb(err, data);
}
});
break;
default:
}
}
})
.catch(function(err) {
logger.error(err);
});
}
var fetchTeamAndCohortPeers = function(fellow, peers, cb) {
models.Team
.findById(fellow.team_id, {
include: [ models.Fellow ]
})
.then(function(team) {
if (team) {
_.each(team.Fellows, function(peer) {
if (peer.uid !== fellow.uid) {
peers.push(peer);
}
})
fetchCohortPeers(fellow, peers, function(err, data) {
if (data) {
cb(err, data);
}
});
}
else {
fetchCohortPeers(fellow, peers, function(err, data) {
if (data) {
cb(err, data);
}
});
}
})
.catch(function(err) {
logger.error(err);
});
};
var fetchCohortPeers = function(fellow, peers, cb) {
models.Cohort
.findById(fellow.cohort_id, {
include: [ models.Fellow ]
})
.then(function(cohort) {
if (cohort) {
_.each(cohort.Fellows, function(peer) {
if (peer.uid !== fellow.uid) {
peers.push(peer);
}
});
cb(null, peers);
}
})
.catch(function(err) {
logger.error(err);
});
};
var fetchAllPeers = function(fellow, peers, cb) {
var where = {
$or: [
{
level: 'D1 Jr Consultant'
},
{
level: 'D2 Consultant'
},
{
level: 'D3 Consultant'
},
{
level: 'D4 Consultant'
}
]
}
models.Fellow
.findAll({
where: where,
order: 'first_name ASC'
})
.then(function(fellows) {
if (fellows) {
_.each(fellows, function(peer) {
if (peer.uid !== fellow.uid) {
peers.push(peer);
};
});
cb(null, peers);
}
})
.catch(function(err) {
logger.error(err);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment