All files / lib/lambda/user-management submitGroupDivision.ts

92.3% Statements 12/13
70% Branches 7/10
100% Functions 1/1
92.3% Lines 12/13

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                1x                         1x               3x 3x 3x   3x       3x   3x 1x           2x   2x                         2x          
import { createError } from "@middy/util";
import { APIGatewayEvent } from "aws-lambda";
import { produceMessage } from "libs/api/kafka";
import { z } from "zod";
 
import { authenticatedMiddy, canViewUser, ContextWithAuthenticatedUser } from "../middleware";
import { getUserByEmail } from "./userManagementService";
 
export const submitGroupDivisionEventSchema = z
  .object({
    body: z.object({
      userEmail: z.string(),
      group: z.string(),
      division: z.string(),
    }),
  })
  .passthrough();
 
export type SubmitGroupDivisionEvent = APIGatewayEvent &
  z.infer<typeof submitGroupDivisionEventSchema>;
 
export const handler = authenticatedMiddy({
  opensearch: true,
  kafka: true,
  setToContext: true,
  eventSchema: submitGroupDivisionEventSchema,
})
  .use(canViewUser())
  .handler(async (event: SubmitGroupDivisionEvent, context: ContextWithAuthenticatedUser) => {
    const { authenticatedUser } = context;
    const { userEmail, group, division } = event.body;
    const lookupEmail = userEmail || authenticatedUser?.email;
 
    Iif (!lookupEmail) {
      throw new Error("Email is undefined");
    }
 
    const userInfo = await getUserByEmail(lookupEmail);
 
    if (!userInfo || userInfo === null) {
      throw createError(
        404,
        JSON.stringify({ message: `User with email ${userEmail} not found.` }),
      );
    }
 
    const { fullName, email, id } = userInfo;
 
    await produceMessage(
      process?.env?.topicName || "",
      userInfo.id,
      JSON.stringify({
        id,
        email,
        group,
        division,
        fullName,
        eventType: "user-info",
      }),
    );
 
    return {
      statusCode: 200,
      body: { message: "Group and division submitted successfully." },
    };
  });