convert_archived_state.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. const STAGE = process.argv.pop()
  7. async function main() {
  8. if (STAGE.includes('FIRST')) {
  9. await batchedUpdate(
  10. 'projects',
  11. { archived: false },
  12. {
  13. $set: { archived: [] },
  14. }
  15. )
  16. console.error('Done, with first part')
  17. }
  18. if (STAGE.includes('SECOND')) {
  19. await batchedUpdate('projects', { archived: true }, performUpdate, {
  20. _id: 1,
  21. owner_ref: 1,
  22. collaberator_refs: 1,
  23. readOnly_refs: 1,
  24. tokenAccessReadAndWrite_refs: 1,
  25. tokenAccessReadOnly_refs: 1,
  26. })
  27. console.error('Done, with second part')
  28. }
  29. }
  30. main()
  31. .then(() => {
  32. process.exit(0)
  33. })
  34. .catch(error => {
  35. console.error({ error })
  36. process.exit(1)
  37. })
  38. async function performUpdate(collection, nextBatch) {
  39. await promiseMapWithLimit(WRITE_CONCURRENCY, nextBatch, project =>
  40. setArchived(collection, project)
  41. )
  42. }
  43. async function setArchived(collection, project) {
  44. const archived = calculateArchivedArray(project)
  45. return collection.updateOne(
  46. { _id: project._id },
  47. {
  48. $set: { archived },
  49. }
  50. )
  51. }
  52. function calculateArchivedArray(project) {
  53. return _.unionWith(
  54. [project.owner_ref],
  55. project.collaberator_refs,
  56. project.readOnly_refs,
  57. project.tokenAccessReadAndWrite_refs,
  58. project.tokenAccessReadOnly_refs,
  59. _objectIdEquals
  60. )
  61. }
  62. function _objectIdEquals(firstVal, secondVal) {
  63. // For use as a comparator for unionWith
  64. return firstVal.toString() === secondVal.toString()
  65. }