以下是一个使用AWS SDK for JavaScript(v3)的示例代码,将ID列表转换为用户属性列表的解决方法:
const { CognitoIdentityProviderClient, ListUsersCommand, AdminGetUserCommand } = require("@aws-sdk/client-cognito-identity-provider");
// 定义 AWS Cognito UserPool 的区域和用户池 ID
const region = "us-west-2";
const userPoolId = "YOUR_USER_POOL_ID";
// 实例化 CognitoIdentityProviderClient
const client = new CognitoIdentityProviderClient({ region });
const getUserAttributes = async (userId) => {
try {
// 使用 ListUsersCommand 获取用户池中的所有用户
const listUsersCommand = new ListUsersCommand({
UserPoolId: userPoolId
});
const { Users } = await client.send(listUsersCommand);
// 找到与给定 userId 匹配的用户
const user = Users.find(u => u.Username === userId);
// 使用 AdminGetUserCommand 获取用户的属性列表
const adminGetUserCommand = new AdminGetUserCommand({
UserPoolId: userPoolId,
Username: user.Username
});
const { UserAttributes } = await client.send(adminGetUserCommand);
// 将用户属性列表转换为键值对对象
const attributes = UserAttributes.reduce((acc, attribute) => {
acc[attribute.Name] = attribute.Value;
return acc;
}, {});
return attributes;
} catch (error) {
console.log("Error:", error);
throw error;
}
};
// 使用示例
const userId = "USER_ID_TO_GET_ATTRIBUTES";
getUserAttributes(userId)
.then(attributes => {
console.log("User Attributes:", attributes);
})
.catch(error => {
console.error("Failed to get user attributes:", error);
});
在上面的代码中,首先实例化 CognitoIdentityProviderClient 并使用 ListUsersCommand 获取用户池中的所有用户。然后,找到与给定的 userId 匹配的用户,并使用 AdminGetUserCommand 获取该用户的属性列表。最后,将属性列表转换为键值对对象并返回。
请确保将 YOUR_USER_POOL_ID 替换为您的实际用户池 ID,并将 USER_ID_TO_GET_ATTRIBUTES 替换为您要获取属性的用户的 ID。