-
-
Save joepie91/e78ca0c9d9831de4c775 to your computer and use it in GitHub Desktop.
Code snippet to demonstrate Promises.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var _ = require('lodash'); | |
var async = require('async'); | |
var moment = require('moment'); | |
var Promise = require('bluebird'); | |
var messaging = require('../../messaging'); | |
var patients = require('../patients'); | |
var practitioners = require('../practitioners'); | |
var dataProvider = require('../../database'); | |
module.exports = function(Events) { | |
Events.cancel = function(data, options) { | |
return Promise.try(function() { | |
var eventIds = data.eventIds; | |
var partnerId = options.context.partnerId; | |
var userId = options.context.userId; | |
var userType = options.context.userType; | |
if (userType === "practitioner") { // ===. not == | |
var practitionerId = userId; | |
} else { | |
var practitionerId = data.practitionerId; | |
} | |
return Promise.each(eventIds, function(eventId) { | |
// assumes that all of the below returns a promise. if not, you need to promisify. | |
return Promise.all([ | |
dataProvider.events.exists(eventId, options), | |
practitioners.exists({ | |
userId: practitionerId, | |
partnerId: partnerId | |
}, options) | |
]).spread(function(event, practitioner) { | |
Promise.try(function() { | |
// only happens when the previous three calls all succeeded | |
return Promise.all([ | |
dataProvider.events.edit(eventId, {status: "cancelled"}, options), | |
patients.exists(event.patientId, options) | |
]); | |
}).spread(function(editResult, patient) { | |
var message = "Dear " + patient.firstName + "," + " " + | |
"your appointment with " + | |
"Dr. " + practitioner.practGivenName + " " + | |
"at " + event.location + " " + | |
"has been CANCELLED for " + | |
moment(event.start).utcOffset(+330).format('MMMM DD YYYY h:mm a') + | |
"."; | |
return messaging.sendMessage({ | |
message: message, | |
number: "+" + patient.phoneNumber | |
}); | |
}).then(function(response){ | |
if (response.statusCode !== 200) { | |
throw new Error("Non-200 status code received (" + response.statusCode + ")") | |
} | |
}); | |
}) | |
}).then(function() { | |
return { | |
message: "Marked event as cancelled" | |
}; | |
}); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment