convert_archived_state.mjs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import _ from 'lodash'
  2. import { db } from '../app/src/infrastructure/mongodb.js'
  3. import BatchedUpdateModule from './helpers/batchedUpdate.mjs'
  4. import { promiseMapWithLimit } from '@overleaf/promise-utils'
  5. import { fileURLToPath } from 'url'
  6. const { batchedUpdate } = BatchedUpdateModule
  7. const WRITE_CONCURRENCY = parseInt(process.env.WRITE_CONCURRENCY, 10) || 10
  8. // $ node scripts/convert_archived_state.mjs FIRST,SECOND
  9. async function main(STAGE) {
  10. for (const FIELD of ['archived', 'trashed']) {
  11. if (STAGE.includes('FIRST')) {
  12. await batchedUpdate(
  13. 'projects',
  14. { [FIELD]: false },
  15. {
  16. $set: { [FIELD]: [] },
  17. }
  18. )
  19. console.error('Done, with first part for field:', FIELD)
  20. }
  21. if (STAGE.includes('SECOND')) {
  22. await batchedUpdate(
  23. 'projects',
  24. { [FIELD]: true },
  25. async function performUpdate(nextBatch) {
  26. await promiseMapWithLimit(
  27. WRITE_CONCURRENCY,
  28. nextBatch,
  29. async project => {
  30. try {
  31. await upgradeFieldToArray({ project, FIELD })
  32. } catch (err) {
  33. console.error(project._id, err)
  34. throw err
  35. }
  36. }
  37. )
  38. },
  39. {
  40. _id: 1,
  41. owner_ref: 1,
  42. collaberator_refs: 1,
  43. readOnly_refs: 1,
  44. tokenAccessReadAndWrite_refs: 1,
  45. tokenAccessReadOnly_refs: 1,
  46. }
  47. )
  48. console.error('Done, with second part for field:', FIELD)
  49. }
  50. }
  51. }
  52. async function upgradeFieldToArray({ project, FIELD }) {
  53. return db.projects.updateOne(
  54. { _id: project._id },
  55. {
  56. $set: { [FIELD]: getAllUserIds(project) },
  57. }
  58. )
  59. }
  60. function getAllUserIds(project) {
  61. return _.unionWith(
  62. [project.owner_ref],
  63. project.collaberator_refs,
  64. project.readOnly_refs,
  65. project.tokenAccessReadAndWrite_refs,
  66. project.tokenAccessReadOnly_refs,
  67. _objectIdEquals
  68. )
  69. }
  70. function _objectIdEquals(firstVal, secondVal) {
  71. // For use as a comparator for unionWith
  72. return firstVal.toString() === secondVal.toString()
  73. }
  74. if (fileURLToPath(import.meta.url) === process.argv[1]) {
  75. try {
  76. await main(process.argv.pop())
  77. process.exit(0)
  78. } catch (error) {
  79. console.error({ error })
  80. process.exit(1)
  81. }
  82. }
  83. export default main