fetch reservations, find and update changed reservations

This commit is contained in:
Bilal Catic
2019-06-27 05:38:45 +02:00
parent aedb09d1be
commit 7aab1e538e
7 changed files with 127 additions and 4 deletions

View File

@@ -0,0 +1,2 @@
'use strict';

View File

@@ -148,11 +148,77 @@ const writeBookingReservation = (bookingReservation) => {
return db.bookingReservation.findOrCreate({where: {...bookingReservation}, defaults: {...bookingReservation}});
};
const bulkWriteReservationsWithChangesTracking = (reservations) => {
return new Promise ((resolve, reject) => {
const changes = [];
const asyncJobs = [];
db.bookingReservation.addHook('beforeUpdate', 'updateHook', (instance) => {
const changedKeys = instance.changed();
const previous = instance.previous();
const indexOfUpdatedAt = changedKeys.indexOf('updatedAt');
if (indexOfUpdatedAt !== -1){
changedKeys.splice(indexOfUpdatedAt, 1);
}
if (changedKeys.length > 0){
//check if there is really difference, reservation start and end timestamps are reported as changed but they are not
let realChange = false;
changedKeys.forEach((changedKey) => {
if (JSON.stringify(previous[changedKey]) !== JSON.stringify(instance[changedKey])){
realChange = true;
}
});
if (realChange){
changes.push({
oldReservation: previous,
newReservation: instance.get(),
});
}
}
});
reservations.forEach((reservation) => {
asyncJobs.push(
db.bookingReservation.update(reservation, {
where: {
reservationId: reservation.reservationId,
},
returning: true,
individualHooks: true,
})
.then(([updateCount, updatedInstances]) => {
if (updateCount === 0){
db.bookingReservation.upsert(reservation);
}
})
.catch((error) => {
console.log('Error updating');
console.log(error);
reject(error);
})
);
});
Promise.all(asyncJobs)
.then(() => {
db.bookingReservation.removeHook('updateHook');
resolve(changes);
})
.catch((error) => reject(error));
});
};
module.exports = {
fetchAllBookings,
writeBookingReservation,
getAllFinishedBookings,
getFirstNextBooking,
getFirstPreviousBooking,
getFirstReservationInBlock
getFirstReservationInBlock,
bulkWriteReservationsWithChangesTracking,
};