Untitled

 avatar
unknown
typescript
23 days ago
2.7 kB
3
Indexable
import { SQSBatchItemFailure, SQSHandler } from "aws-lambda";
import { ConditionalCheckFailedException } from "@aws-sdk/client-dynamodb";

import { UpsertZohoDeskTicketCommand } from "@/lib/services/zoho-desk-integration/commands/lambda/upsert-zoho-desk-ticket.command";

import { ZohoDeskTicketEvent } from '../types';

type ZohoDeskEvent = ZohoDeskTicketEvent;

export const handler: SQSHandler = async (event) => {
  const batchItemFailures: SQSBatchItemFailure[] = [];

  await Promise.all((event.Records || []).map(async (record) => {
    try {
      const { payload }: ZohoDeskEvent = JSON.parse(record.body);
      
      const modifiedTime = payload.modifiedTime ? new Date(payload.modifiedTime).getTime() : 0;
      
      const command = new UpsertZohoDeskTicketCommand({
        assigneeEmail: payload.assignee?.email || undefined,
        assigneeZohoUserId: payload.assigneeId || undefined,
        compoundOrderStatus: payload.cf?.cf_compound_order_status || undefined,
        compoundPaidStatus: payload.cf?.cf_compound_paid_status || undefined,
        createdAt: payload.createdTime,
        dueDate: payload.dueDate || undefined,
        healthieChartId: payload.cf?.cf_chart_id || undefined,
        healthieOrganizationId: payload.cf?.cf_org_id || undefined,
        healthiePatientId: payload.cf?.cf_patient_id || undefined,
        id: payload.id,
        isArchived: payload.isArchived,
        isDeleted: payload.isDeleted,
        isOverdue: payload.isOverDue,
        modality: payload.cf?.cf_modality || undefined,
        modifiedBy: payload.modifiedBy,
        programName: payload.cf?.cf_program_name || undefined,
        resolutionStatus: payload.cf?.cf_resolution_status || undefined,
        serviceDepartment: payload.cf?.cf_service_department || undefined,
        serviceRequestDepartmentType: payload.cf?.cf_service_request_department_type || undefined,
        status: payload.status,
        subject: payload.subject,
        ticketNumber: payload.ticketNumber,
        tier: payload.cf?.cf_tier || undefined,
        updatedAt: payload.modifiedTime,
        webUrl: payload.webUrl,
        eventTimestamp: modifiedTime,
      });
  
      await command.execute();

      console.log(`Successfully processed ticket ${payload.id}`);
      
    } catch (error) {
      if (error instanceof ConditionalCheckFailedException) {
        console.log(`Skipping processing for ticket ${JSON.parse(record.body).payload.id} as a newer event has already been processed`);
        return;
      }
      
      console.error('Error processing record', record, error);
      batchItemFailures.push({
        itemIdentifier: record.messageId,
      });
    }
  }));

  return {
    batchItemFailures,
  };
};
Editor is loading...
Leave a Comment