-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgetAllStateUsers.ts
57 lines (53 loc) · 1.69 KB
/
getAllStateUsers.ts
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
import {
CognitoIdentityProviderClient,
ListUsersCommand,
ListUsersCommandInput,
ListUsersCommandOutput,
} from "@aws-sdk/client-cognito-identity-provider";
export type StateUser = {
firstName: string;
lastName: string;
email: string;
formattedEmailAddress: string;
};
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.Name === "custom:state");
return stateAttribute?.Value?.split(",").includes(state);
}).map((user) => {
const attributes = user.Attributes?.reduce((acc, attr) => {
acc[attr.Name as any] = attr.Value;
return acc;
}, {} as Record<string, string | undefined>);
return {
firstName: attributes?.["given_name"],
lastName: attributes?.["family_name"],
email: attributes?.["email"],
formattedEmailAddress: `${attributes?.["given_name"]} ${attributes?.["family_name"]} <${attributes?.["email"]}>`,
};
});
return filteredStateUsers as StateUser[];
} catch (error) {
console.error("Error fetching users:", error);
throw new Error("Error fetching users");
}
};