ThreadManager.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import { db, ObjectId } from '../../mongodb.js'
  2. export const GLOBAL_THREAD = 'GLOBAL'
  3. export async function findOrCreateThread(projectId, threadId) {
  4. let query, update
  5. projectId = ObjectId(projectId.toString())
  6. if (threadId !== GLOBAL_THREAD) {
  7. threadId = ObjectId(threadId.toString())
  8. }
  9. if (threadId === GLOBAL_THREAD) {
  10. query = {
  11. project_id: projectId,
  12. thread_id: { $exists: false },
  13. }
  14. update = {
  15. project_id: projectId,
  16. }
  17. } else {
  18. query = {
  19. project_id: projectId,
  20. thread_id: threadId,
  21. }
  22. update = {
  23. project_id: projectId,
  24. thread_id: threadId,
  25. }
  26. }
  27. const result = await db.rooms.findOneAndUpdate(
  28. query,
  29. { $set: update },
  30. { upsert: true, returnDocument: 'after' }
  31. )
  32. return result.value
  33. }
  34. export async function findAllThreadRooms(projectId) {
  35. return db.rooms
  36. .find(
  37. {
  38. project_id: ObjectId(projectId.toString()),
  39. thread_id: { $exists: true },
  40. },
  41. {
  42. thread_id: 1,
  43. resolved: 1,
  44. }
  45. )
  46. .toArray()
  47. }
  48. export async function findAllThreadRoomsAndGlobalThread(projectId) {
  49. return db.rooms
  50. .find(
  51. {
  52. project_id: ObjectId(projectId.toString()),
  53. },
  54. {
  55. thread_id: 1,
  56. resolved: 1,
  57. }
  58. )
  59. .toArray()
  60. }
  61. export async function resolveThread(projectId, threadId, userId) {
  62. await db.rooms.updateOne(
  63. {
  64. project_id: ObjectId(projectId.toString()),
  65. thread_id: ObjectId(threadId.toString()),
  66. },
  67. {
  68. $set: {
  69. resolved: {
  70. user_id: userId,
  71. ts: new Date(),
  72. },
  73. },
  74. }
  75. )
  76. }
  77. export async function reopenThread(projectId, threadId) {
  78. await db.rooms.updateOne(
  79. {
  80. project_id: ObjectId(projectId.toString()),
  81. thread_id: ObjectId(threadId.toString()),
  82. },
  83. {
  84. $unset: {
  85. resolved: true,
  86. },
  87. }
  88. )
  89. }
  90. export async function deleteThread(projectId, threadId) {
  91. const room = await findOrCreateThread(projectId, threadId)
  92. await db.rooms.deleteOne({
  93. _id: room._id,
  94. })
  95. return room._id
  96. }
  97. export async function deleteAllThreadsInProject(projectId) {
  98. await db.rooms.deleteMany({
  99. project_id: ObjectId(projectId.toString()),
  100. })
  101. }