SnapshotManager.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* eslint-disable
  2. camelcase,
  3. no-return-assign,
  4. */
  5. // TODO: This file was created by bulk-decaffeinate.
  6. // Fix any style issues and re-enable lint.
  7. /*
  8. * decaffeinate suggestions:
  9. * DS101: Remove unnecessary use of Array.from
  10. * DS102: Remove unnecessary code created because of implicit returns
  11. * DS207: Consider shorter variations of null checks
  12. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  13. */
  14. let SnapshotManager
  15. const { db, ObjectId } = require('./mongodb')
  16. module.exports = SnapshotManager = {
  17. recordSnapshot(
  18. project_id,
  19. doc_id,
  20. version,
  21. pathname,
  22. lines,
  23. ranges,
  24. callback
  25. ) {
  26. try {
  27. project_id = ObjectId(project_id)
  28. doc_id = ObjectId(doc_id)
  29. } catch (error) {
  30. return callback(error)
  31. }
  32. db.docSnapshots.insertOne(
  33. {
  34. project_id,
  35. doc_id,
  36. version,
  37. lines,
  38. pathname,
  39. ranges: SnapshotManager.jsonRangesToMongo(ranges),
  40. ts: new Date(),
  41. },
  42. callback
  43. )
  44. },
  45. // Suggested indexes:
  46. // db.docSnapshots.createIndex({project_id:1, doc_id:1})
  47. // db.docSnapshots.createIndex({ts:1},{expiresAfterSeconds: 30*24*3600)) # expires after 30 days
  48. jsonRangesToMongo(ranges) {
  49. if (ranges == null) {
  50. return null
  51. }
  52. const updateMetadata = function (metadata) {
  53. if ((metadata != null ? metadata.ts : undefined) != null) {
  54. metadata.ts = new Date(metadata.ts)
  55. }
  56. if ((metadata != null ? metadata.user_id : undefined) != null) {
  57. return (metadata.user_id = SnapshotManager._safeObjectId(
  58. metadata.user_id
  59. ))
  60. }
  61. }
  62. for (const change of Array.from(ranges.changes || [])) {
  63. change.id = SnapshotManager._safeObjectId(change.id)
  64. updateMetadata(change.metadata)
  65. }
  66. for (const comment of Array.from(ranges.comments || [])) {
  67. comment.id = SnapshotManager._safeObjectId(comment.id)
  68. if ((comment.op != null ? comment.op.t : undefined) != null) {
  69. comment.op.t = SnapshotManager._safeObjectId(comment.op.t)
  70. }
  71. updateMetadata(comment.metadata)
  72. }
  73. return ranges
  74. },
  75. _safeObjectId(data) {
  76. try {
  77. return ObjectId(data)
  78. } catch (error) {
  79. return data
  80. }
  81. },
  82. }