applyTimestampsToUpdate.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. const get = require('../get');
  6. module.exports = applyTimestampsToUpdate;
  7. /*!
  8. * ignore
  9. */
  10. function applyTimestampsToUpdate(now, createdAt, updatedAt, currentUpdate, options) {
  11. const updates = currentUpdate;
  12. let _updates = updates;
  13. const overwrite = get(options, 'overwrite', false);
  14. const timestamps = get(options, 'timestamps', true);
  15. // Support skipping timestamps at the query level, see gh-6980
  16. if (!timestamps || updates == null) {
  17. return currentUpdate;
  18. }
  19. const skipCreatedAt = timestamps != null && timestamps.createdAt === false;
  20. const skipUpdatedAt = timestamps != null && timestamps.updatedAt === false;
  21. if (overwrite) {
  22. if (currentUpdate && currentUpdate.$set) {
  23. currentUpdate = currentUpdate.$set;
  24. updates.$set = {};
  25. _updates = updates.$set;
  26. }
  27. if (!skipUpdatedAt && updatedAt && !currentUpdate[updatedAt]) {
  28. _updates[updatedAt] = now;
  29. }
  30. if (!skipCreatedAt && createdAt && !currentUpdate[createdAt]) {
  31. _updates[createdAt] = now;
  32. }
  33. return updates;
  34. }
  35. currentUpdate = currentUpdate || {};
  36. if (Array.isArray(updates)) {
  37. // Update with aggregation pipeline
  38. updates.push({ $set: { updatedAt: now } });
  39. return updates;
  40. }
  41. updates.$set = updates.$set || {};
  42. if (!skipUpdatedAt && updatedAt &&
  43. (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) {
  44. updates.$set[updatedAt] = now;
  45. if (updates.hasOwnProperty(updatedAt)) {
  46. delete updates[updatedAt];
  47. }
  48. }
  49. if (!skipCreatedAt && createdAt) {
  50. if (currentUpdate[createdAt]) {
  51. delete currentUpdate[createdAt];
  52. }
  53. if (currentUpdate.$set && currentUpdate.$set[createdAt]) {
  54. delete currentUpdate.$set[createdAt];
  55. }
  56. updates.$setOnInsert = updates.$setOnInsert || {};
  57. updates.$setOnInsert[createdAt] = now;
  58. }
  59. if (Object.keys(updates.$set).length === 0) {
  60. delete updates.$set;
  61. }
  62. return updates;
  63. }