convert_archived_state.js 2.2 KB

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