Skip to content

Instantly share code, notes, and snippets.

@brandon-beacher
Created August 1, 2016 21:06
Show Gist options
  • Save brandon-beacher/779dc8e5257eb3ac52da167ec9bc614f to your computer and use it in GitHub Desktop.
Save brandon-beacher/779dc8e5257eb3ac52da167ec9bc614f to your computer and use it in GitHub Desktop.
var Bluebird = require("bluebird");
var GoogleCalendarQueue = require.main.require("./workers/lib/queue")("google_calendar_queue");
var Thinky = require("../../thinky");
var GoogleCalendarEventUpsertion = require("../../google/calendar/event_upsertion");
var Log = require("./log").namespace({ operation: "events_initialization" });
function GoogleCalendarEventsInitialization(googleCalendarId) {
var googleCalendarEvent;
function getNextUninitializedGoogleCalendarEvent() {
return Thinky.r.table("google_calendar_events")
.getAll(
[ googleCalendarId, "uninitialized" ],
{ index: "googleCalendarId|status" }
)
.limit(1)
.update(
{ status: "initializing" },
{ returnChanges: true }
)
.then(function (result) {
if (result.replaced === 1) {
googleCalendarEvent = result.changes[0].new_val;
return googleCalendarEvent;
}
if (result.replaced === 0) {
googleCalendarEvent = null;
return googleCalendarEvent;
}
Log.log({
event: "getting_next_uninitialized_google_calendar_event",
googleCalendarId: googleCalendarId
});
Log.log(result);
throw new Error(
"Expected to replace zero or one documents. Replaced " +
result.replaced +
" instead."
);
});
}
function upsertGoogleCalendarEvent() {
Log.log({
event: "upserting",
googleCalendarId: googleCalendarEvent.googleCalendarId,
bookingId: googleCalendarEvent.bookingId
});
return GoogleCalendarEventUpsertion(
googleCalendarEvent.googleCalendarId,
googleCalendarEvent.bookingId,
"initialized"
);
}
function queueNextEventsInitialization() {
return GoogleCalendarQueue.add({
operation: "initialize_events",
googleCalendarId: googleCalendarId
});
}
function logAndQueueNextEventsInitialization(err) {
Log.log({
event: "failed",
googleCalendarId: googleCalendarEvent.googleCalendarId,
bookingId: googleCalendarEvent.bookingId
});
Log.error(err);
return queueNextEventsInitialization();
}
function initializeGoogleCalendarEvent() {
if (googleCalendarEvent) {
return upsertGoogleCalendarEvent()
.then(queueNextEventsInitialization)
.catch(logAndQueueNextEventsInitialization);
}
return Bluebird.resolve();
}
return getNextUninitializedGoogleCalendarEvent()
.then(initializeGoogleCalendarEvent);
}
module.exports = GoogleCalendarEventsInitialization;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment