convert_archived_state.js 2.2 KB

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