v2_doc_versions.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // @ts-check
  2. 'use strict'
  3. const _ = require('lodash')
  4. /**
  5. * @import File from "./file"
  6. * @import Snapshot from "./snapshot"
  7. * @import { RawV2DocVersions } from "./types"
  8. */
  9. class V2DocVersions {
  10. /**
  11. * @param {RawV2DocVersions} data
  12. */
  13. constructor(data) {
  14. this.data = data || {}
  15. }
  16. /**
  17. * @param {RawV2DocVersions?} [raw]
  18. * @return {V2DocVersions|undefined}
  19. */
  20. static fromRaw(raw) {
  21. if (!raw) return undefined
  22. return new V2DocVersions(raw)
  23. }
  24. /**
  25. * @return {?RawV2DocVersions}
  26. */
  27. toRaw() {
  28. if (!this.data) return null
  29. const raw = _.clone(this.data)
  30. return raw
  31. }
  32. /**
  33. * Clone this object.
  34. *
  35. * @return {V2DocVersions|undefined} a new object of the same type
  36. */
  37. clone() {
  38. return V2DocVersions.fromRaw(this.toRaw())
  39. }
  40. /**
  41. * @param {Snapshot} snapshot
  42. */
  43. applyTo(snapshot) {
  44. // Only update the snapshot versions if we have new versions
  45. if (!_.size(this.data)) return
  46. // Create v2DocVersions in snapshot if it does not exist
  47. // otherwise update snapshot v2docversions
  48. if (!snapshot.v2DocVersions) {
  49. snapshot.v2DocVersions = this.clone()
  50. } else {
  51. _.assign(snapshot.v2DocVersions.data, this.data)
  52. }
  53. }
  54. /**
  55. * Move or remove a doc.
  56. * Must be called after FileMap#moveFile, which validates the paths.
  57. * @param {string} pathname
  58. * @param {string} newPathname
  59. */
  60. moveFile(pathname, newPathname) {
  61. for (const [id, v] of Object.entries(this.data)) {
  62. if (v.pathname !== pathname) continue
  63. if (newPathname === '') {
  64. delete this.data[id]
  65. } else {
  66. v.pathname = newPathname
  67. }
  68. break
  69. }
  70. }
  71. }
  72. module.exports = V2DocVersions