fix_comment_id.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // @ts-check
  2. import minimist from 'minimist'
  3. import DocstoreManager from '../app/src/Features/Docstore/DocstoreManager.mjs'
  4. import { db, ObjectId } from '../app/src/infrastructure/mongodb.mjs'
  5. const OPTS = parseArgs()
  6. function usage() {
  7. console.error('Usage: node fix_comment_id.mjs [--commit] PROJECT_ID...')
  8. }
  9. function parseArgs() {
  10. const args = minimist(process.argv.slice(2), {
  11. boolean: ['commit'],
  12. })
  13. if (args._.length === 0) {
  14. usage()
  15. process.exit(0)
  16. }
  17. return {
  18. projectIds: args._,
  19. commit: args.commit,
  20. }
  21. }
  22. /**
  23. * @param {any} projectId
  24. */
  25. async function processProject(projectId) {
  26. console.log(`Processing project ${projectId}...`)
  27. const docRanges = await DocstoreManager.promises.getAllRanges(projectId)
  28. let commentsUpdated = 0
  29. for (const doc of docRanges) {
  30. const updateCommentsInDoc = await processDoc(doc)
  31. commentsUpdated += updateCommentsInDoc
  32. }
  33. if (OPTS.commit) {
  34. console.log(`${commentsUpdated} comments updated`)
  35. }
  36. }
  37. /**
  38. * @param {any} doc
  39. */
  40. async function processDoc(doc) {
  41. let commentsUpdated = 0
  42. for (const comment of doc.ranges.comments ?? []) {
  43. if (comment.op.t !== comment.id) {
  44. console.log(
  45. `updating comment id ${comment.id} to ${comment.op.t} in doc ${doc._id} ...`
  46. )
  47. if (OPTS.commit) {
  48. await db.docs.updateOne(
  49. { _id: new ObjectId(doc._id) },
  50. {
  51. $set: {
  52. 'ranges.comments.$[element].id': new ObjectId(comment.op.t),
  53. },
  54. },
  55. {
  56. arrayFilters: [
  57. { 'element.op.t': { $eq: new ObjectId(comment.op.t) } },
  58. ],
  59. }
  60. )
  61. commentsUpdated += 1
  62. } else {
  63. console.log(
  64. `Would update comment id ${comment.id} to ${comment.op.t} (dry run)`
  65. )
  66. }
  67. }
  68. }
  69. return commentsUpdated
  70. }
  71. // Main loop
  72. for (const projectId of OPTS.projectIds) {
  73. await processProject(projectId)
  74. }
  75. if (!OPTS.commit) {
  76. console.log('This was a dry run. Rerun with --commit to apply changes')
  77. }
  78. process.exit(0)