eletrotupi / tcc/ api/src/lib/queue/processors/exports.ts19821da369359c6ba1cc9b4afa45b47d0e72f116
1.2 KB | 49 lines Raw
1
import { Job } from "bullmq";
2

3
import {
4
  ExportJobData,
5
  ExportJobName,
6
  ExportPayload,
7
} from "@app/lib/queue/types";
8
import { buildExportArchive } from "@app/services/export/export.service";
9
import {
10
  sendExportFailedEmail,
11
  sendExportReadyEmail,
12
} from "@app/services/mail";
13

14
export async function exportProcessor(
15
  job: Job<ExportJobData["data"]>,
16
): Promise<void> {
17
  switch (job.name as ExportJobName) {
18
    case ExportJobName.Data: {
19
      const { userId } = job.data as ExportPayload;
20

21
      try {
22
        const archive = await buildExportArchive(userId);
23
        await sendExportReadyEmail(userId, archive);
24
      } catch (err) {
25
        // Only the last attempt notifies the user; earlier ones are retried
26
        const attempts = job.opts.attempts ?? 1;
27
        const isFinalAttempt = job.attemptsMade + 1 >= attempts;
28

29
        if (isFinalAttempt) {
30
          try {
31
            await sendExportFailedEmail(userId);
32
          } catch (mailErr) {
33
            console.error(
34
              `[exports] failed to send the failure email for user ${userId}:`,
35
              mailErr,
36
            );
37
          }
38
        }
39

40
        throw err;
41
      }
42

43
      break;
44
    }
45

46
    default:
47
      throw new Error(`Unknown export job: ${job.name}`);
48
  }
49
}