Skip to content

Instantly share code, notes, and snippets.

@joepie91
Forked from horsey/gist:96ce0a9db9e66090288d
Last active December 11, 2015 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joepie91/e78ca0c9d9831de4c775 to your computer and use it in GitHub Desktop.
Save joepie91/e78ca0c9d9831de4c775 to your computer and use it in GitHub Desktop.
Code snippet to demonstrate Promises.
'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