canezzy

Untitled

Apr 18th, 2019
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. 'use strict';
  2.  
  3. // SQL car reservation before-hook
  4. module.exports = function(Mcarreservation) {
  5. Mcarreservation.beforeRemote('create',
  6. function(ctx, model, next) {
  7.  
  8. Promise.try(doReservation(Mcarreservation, ctx, model, next)).catch(
  9. (e) => {
  10. e.statusCode = e.status = 404;
  11. next(e);
  12. return;
  13. }
  14. );
  15. });
  16. };
  17.  
  18. function doReservation(Mcarreservation, ctx, model, next) {
  19. // models
  20. var sqlCarReservation = Mcarreservation.app.models.CarReservation;
  21. var sCar = Mcarreservation.app.models.sCar;
  22. // data source
  23. var postgres = sCar.app.dataSources.postgres;
  24. // begin transaction
  25. sqlCarReservation.beginTransaction({
  26. isolationLevel: sqlCarReservation.Transaction.READ_COMMITTED,
  27. }, function(err, tx) {
  28. if (err) throw err;
  29. // lock car for update
  30. postgres.connector.execute(
  31. 'SELECT * FROM sCar WHERE mongoId = $1 FOR UPDATE;'
  32. , [ctx.req.body.carId], function(err, data) {
  33. sCar.findOne({where: {mongoId: ctx.req.body.carId}}).then((car)=>{
  34. sqlCarReservation.find(
  35. {
  36. where: {sCarId: car.id},
  37. }).then((data)=> {
  38. data.forEach((element) => {
  39. var start1 = element.startDate.getTime();
  40. var end1 = element.endDate.getTime();
  41. var start2 = ctx.req.body.startDate;
  42. var end2 = ctx.req.body.endDate;
  43. if ((start1 >= start2 && start1 <= end2) ||
  44. (start2 >= start1 && start2 <= end1)) {
  45. tx.rollback(function(err) {
  46. if (err) throw err;
  47.  
  48. var error = new Error('Car is already reserved');
  49.  
  50. throw error;
  51. });
  52. }
  53. });
  54.  
  55. if (err) {
  56. tx.rollback(function(err) {
  57. if (err) throw err;
  58. });
  59. throw err;
  60. }
  61. // fetch car from sql
  62. sCar.findOne({where: {mongoId: ctx.req.body.carId}})
  63. .then((car)=>{
  64. // create reservation
  65. sqlCarReservation.create(
  66. {
  67. timeStamp: ctx.req.body.timeStamp,
  68. sCar: car,
  69. startDate: ctx.req.body.startDate,
  70. endDate: ctx.req.body.endDate,
  71. },
  72. {transaction: tx},
  73. function(err, cr) {
  74. if (err) {
  75. tx.rollback(function(err) {
  76. if (err) throw err;
  77. });
  78. throw err;
  79. }
  80. // commit and end before-hook
  81. tx.commit(function(err) {
  82. if (err) throw err;
  83. next();
  84. });
  85. });
  86. });
  87. });
  88. });
  89. });
  90. });
  91. }
Advertisement
Add Comment
Please, Sign In to add comment