All files / lib/libs/email getAllStateUsers.ts

89.18% Statements 33/37
83.33% Branches 15/18
87.5% Functions 7/8
88.88% Lines 32/36

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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117                                                  5x             6x 6x       6x 6x     6x   5x 1x     4x 92x 452x   92x   5x 33x 33x   33x       5x 1x 1x       4x 4x 1x 1x     3x   3x               5x   1x 1x       5x                 26x 26x   26x                            
import {
  AttributeType,
  CognitoIdentityProviderClient,
  ListUsersCommand,
  ListUsersCommandInput,
  ListUsersCommandOutput,
} from "@aws-sdk/client-cognito-identity-provider";
 
import { getStateUsersByState } from "../../lambda/user-management/userManagementService";
 
export type StateUser = {
  firstName: string;
  lastName: string;
  email: string;
  formattedEmailAddress: string;
};
 
type CognitoUserAttributes = {
  email?: string;
  given_name?: string;
  family_name?: string;
  "custom:state"?: string;
  [key: string]: string | undefined;
};
 
export const getAllStateUsers = async ({
  userPoolId,
  state,
}: {
  userPoolId: string;
  state: string;
}): Promise<StateUser[]> => {
  try {
    const params: ListUsersCommandInput = {
      UserPoolId: userPoolId,
      Limit: 60,
    };
    const command = new ListUsersCommand(params);
    const cognitoClient = new CognitoIdentityProviderClient({
      region: process.env.region,
    });
    const response: ListUsersCommandOutput = await cognitoClient.send(command);
 
    if (!response.Users || response.Users.length === 0) {
      return [];
    }
 
    const filteredStateUsers = response.Users.filter((user) => {
      const stateAttribute = user.Attributes?.find(
        (attr): attr is AttributeType => attr.Name === "custom:state" && attr.Value !== undefined,
      );
      return stateAttribute?.Value?.split(",").includes(state);
    }).map((user) => {
      const attributes = user.Attributes?.reduce<CognitoUserAttributes>((acc, attr) => {
        Eif (attr.Name && attr.Value) {
          acc[attr.Name] = attr.Value;
        }
        return acc;
      }, {});
 
      // Skip users without valid email components
      if (!attributes?.email) {
        console.error(`No email found for user: ${JSON.stringify(user, null, 2)}`);
        return null;
      }
 
      // Validate email format
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(attributes.email)) {
        console.error(`Invalid email format for user: ${attributes.email}`);
        return null;
      }
 
      const formattedEmailAddress = `${attributes.given_name} ${attributes.family_name} <${attributes.email}>`;
 
      return {
        firstName: attributes.given_name ?? "",
        lastName: attributes.family_name ?? "",
        email: attributes.email,
        formattedEmailAddress,
      };
    });
 
    return filteredStateUsers.filter((user): user is StateUser => user !== null);
  } catch (error) {
    console.error("Error fetching users:", error);
    throw new Error("Error fetching users");
  }
};
 
export const getAllStateUsersFromOpenSearch = async (
  state: string,
): Promise<
  {
    formattedEmailAddress: string;
    email: string;
    fullName: string;
  }[]
> => {
  try {
    const stateUsers = await getStateUsersByState(state);
 
    return stateUsers.map(({ fullName, email }) => {
      const formattedEmailAddress = `${fullName} <${email}>`;
 
      return {
        fullName,
        email,
        formattedEmailAddress,
      };
    });
  } catch (error) {
    console.error("Error fetching users:", error);
    throw new Error("Error fetching users");
  }
};