Skip to content

Instantly share code, notes, and snippets.

@calvintwr
Created December 2, 2015 12:59
Show Gist options
  • Save calvintwr/bb1eeb0f66e2840d6a35 to your computer and use it in GitHub Desktop.
Save calvintwr/bb1eeb0f66e2840d6a35 to your computer and use it in GitHub Desktop.
/**
* @api {get} /chat/one Retrieve one chat.
* @apiName GetOneChat
* @apiGroup Chat
*
* @apiParam {int} [chatId] Providing chatId alone is sufficient. Else provide travellerId, shopperId and requestId.
* @apiParam {int} [travellerId]
* @apiParam {int} [shopperId]
* @apiParam {int} [requestId]
*
* @apiSuccess {Bool} success success flag.
* @apiSuccess {JSON} chat
*/
router.get('/one', function(req, res) {
var errLocation = fname + ' index/one';
var where = {};
var chatId = req.query.chatId;
if (chatId) {
// case 1: using chatId
if (!parseInt(chatId)) {
return res.status(400).send({
success: false,
message: 'An error has occurred, please try again.',
debug: {
message: '`chatId` parameter is not valid.'
}
});
}
where.chatId = chatId;
} else {
// case 2: using travellerId, shopperId and requestId as a set.
var travellerId = req.query.travellerId,
shopperId = req.query.shopperId,
requestId = req.query.requestId;
if (!travellerId || !parseInt(travellerId)) {
return res.status(400).send({
success: false,
message: 'An error has occurred, please try again.',
debug: {
message: '`travellerId` parameter is not valid.'
}
});
}
if (!shopperId || !parseInt(shopperId)) {
return res.status(400).send({
success: false,
message: 'An error has occurred, please try again.',
debug: {
message: '`shopperId` parameter is not valid.'
}
});
}
if (!requestId || !parseInt(requestId)) {
return res.status(400).send({
success: false,
message: 'An error has occurred, please try again.',
debug: {
message: '`requestId` parameter is not valid.'
}
});
}
where.User_userId__shopper = shopperId;
where.User_userId__traveller = travellerId;
where.Request_requestId = requestId;
}
DB.Chat.findOne({
where: where,
include: [{
model: DB.User,
as: 'Traveller'
}, {
model: DB.User,
as: 'Shopper'
}, {
model: DB.ChatLine
}, {
model: DB.Request
}],
order: [
[{ model: DB.ChatLine }, 'lineId', 'DESC']
]
}).then(function(chat) {
if (!chat) {
return res.status(400).send({
success: false,
message: 'An error has occurred, please try again.',
debug: {
message: '`chat` was not found.'
}
});
}
res.send({ success: true, message: '', chat: chat });
// update the unseen counter to zero for this chat.
// don't return this branch to the main promise chain, to isolate error handling.
chat.unseenCounter = 0;
chat.save().catch(function(err) {
ERR_HANDLER(err, null, {
printTrace: true,
useUUID: true,
errLocation: errLocation
});
});
}).catch(function(err) {
ERR_HANDLER(err, res, {
printTrace: true,
useUUID: true,
errLocation: errLocation
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment