All files / lib/lambda utils.ts

100% Statements 16/16
84.21% Branches 16/19
100% Functions 2/2
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                    9x 8x 8x 6x               2x                                 9x 31x           27x     4x 4x   4x 2x 2x       2x         2x       2x    
import { UTCDate } from "@date-fns/utc";
import { errors as OpensearchErrors } from "@opensearch-project/opensearch";
import { add, differenceInDays } from "date-fns";
import { ItemResult } from "shared-types/opensearch/main";
 
export type ErrorResponse = {
  statusCode: number;
  body: {
    message?: string;
  };
};
 
interface ParsedKafkaEvent {
  event?: string;
  authority?: string;
  timestamp: number;
}
 
export const handleOpensearchError = (error: unknown): ErrorResponse => {
  console.error({ error });
  if (error instanceof OpensearchErrors.ResponseError) {
    return {
      statusCode: error.statusCode || error.meta?.statusCode || 500,
      body: {
        message: error.body || error.meta?.body,
      },
    };
  }
 
  return {
    statusCode: 500,
    body: { message: "Internal server error" },
  };
};
 
/**
 * Adjusts the timestamp, if needed, to provide the email template with the correct date.
 * For example:
 * - The 90 day date for a respond to RAI events for CHIP SPAs should not be the timestamp
 * the call to the handler, but the submission date plus the number of days between the
 * RAI request and response.
 * @param parsedRecord the Kafka value parsed as a JSON object
 * @param item the OpenSearch item matching the Kafka key
 * @param timestamp the timestamp of the call to the handler
 * @returns the original timestamp, unless the record is a Respond to RAI event for a CHIP SPA.
 */
export const adjustTimestamp = (parsedRecord: ParsedKafkaEvent, item: ItemResult): number => {
  if (
    !(
      parsedRecord?.event === "respond-to-rai" &&
      parsedRecord?.authority?.toUpperCase() === "CHIP SPA"
    )
  ) {
    return parsedRecord.timestamp;
  }
 
  const submissionDate = item?._source.submissionDate || "";
  const raiRequestedDate = item?._source.raiRequestedDate || "";
 
  if (!submissionDate || !raiRequestedDate) {
    console.error("error parsing os record");
    return parsedRecord.timestamp;
  }
 
  // length of time from when the RAI was requested until now
  const pausedDuration = differenceInDays(
    new UTCDate(), // now
    new UTCDate(raiRequestedDate), // original RAI Requested Date
  );
 
  const submissionDateWithPauseDuration = add(new UTCDate(submissionDate), {
    days: pausedDuration,
  });
 
  return submissionDateWithPauseDuration.getTime();
};