| 328 | * @return {Promise<{taskRequest: Object}>} |
| 329 | */ |
| 330 | const addOrUpdate = async (taskId, userId) => { |
| 331 | try { |
| 332 | const taskRequestsSnapshot = await taskRequestsCollection.where("taskId", "==", taskId).get(); |
| 333 | const [taskRequestRef] = taskRequestsSnapshot.docs; |
| 334 | const taskRequestData = taskRequestRef?.data(); |
| 335 | |
| 336 | if (taskRequestData) { |
| 337 | const currentRequestors = taskRequestData.requestors; |
| 338 | const alreadyRequesting = currentRequestors.some((requestor) => requestor === userId); |
| 339 | if (alreadyRequesting) { |
| 340 | return { alreadyRequesting }; |
| 341 | } |
| 342 | |
| 343 | const updatedRequestors = [...currentRequestors, userId]; |
| 344 | await taskRequestsCollection.doc(taskRequestRef.id).update({ requestors: updatedRequestors }); |
| 345 | |
| 346 | return { |
| 347 | isCreate: false, |
| 348 | requestors: updatedRequestors, |
| 349 | }; |
| 350 | } |
| 351 | |
| 352 | const newTaskRequest = { |
| 353 | requestors: [userId], |
| 354 | status: TASK_REQUEST_STATUS.WAITING, |
| 355 | taskId, |
| 356 | }; |
| 357 | |
| 358 | const newTaskRequestRef = await taskRequestsCollection.add(newTaskRequest); |
| 359 | |
| 360 | return { |
| 361 | isCreate: true, |
| 362 | taskRequest: newTaskRequest, |
| 363 | id: newTaskRequestRef.id, |
| 364 | }; |
| 365 | } catch (err) { |
| 366 | logger.error("Error in updating task", err); |
| 367 | throw err; |
| 368 | } |
| 369 | }; |
| 370 | |
| 371 | /** |
| 372 | * Approve task request for a user. |