eletrotupi / tcc/ api/src/lib/queue/processors/exports.tsb44450051fd5637c480a9dec8ae1f93921d1754c
1.3 KB | 50 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
import { logger } from "@app/lib/logger";
14

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

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

30
        if (isFinalAttempt) {
31
          try {
32
            await sendExportFailedEmail(userId);
33
          } catch (mailErr) {
34
            logger.error(
35
              { err: mailErr, userId },
36
              "[exports] failed to send the failure email",
37
            );
38
          }
39
        }
40

41
        throw err;
42
      }
43

44
      break;
45
    }
46

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