use reqwest::StatusCode;
use uuid::Uuid;
use crate::{
config::data::{SharedHttpClient, SharedKeycloakApi, SharedPool},
error::ServiceError,
keycloak_api::dtos::UserDto,
model::{
dto::{PageParameters, UserSearchParameters, UsersDto},
entity::Users,
},
};
pub async fn create(
user_id: Uuid,
user_data: UsersDto,
pool: &SharedPool,
) -> Result<UsersDto, ServiceError> {
let mut conn = pool.get().await?;
let result = Users::create(user_data, user_id, &mut conn).await?;
Ok(result)
}
pub async fn find_by_id(
user_id: Uuid,
keycloak_api: &SharedKeycloakApi,
http_client: &SharedHttpClient,
) -> Result<UserDto, ServiceError> {
let user = keycloak_api
.get_user_by_id(http_client, user_id)
.await
.map_err(|e| {
log::error!("Error getting user data from Keycloak API: {e}");
ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"Error getting user data from Keycloak API",
)
})?;
Ok(user)
}
pub async fn find_by_ids(
user_ids: Vec<Uuid>,
keycloak_api: &SharedKeycloakApi,
http_client: &SharedHttpClient,
) -> Result<Vec<UserDto>, ServiceError> {
let users = keycloak_api
.get_users_by_ids(http_client, user_ids)
.await
.map_err(|e| {
log::error!("Error getting user data from Keycloak API: {e}");
ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"Error getting user data from Keycloak API",
)
})?;
Ok(users)
}
pub async fn search_by_username(
search_params: &UserSearchParameters,
pagination: &PageParameters,
user_id: Uuid,
keycloak_api: &SharedKeycloakApi,
http_client: &SharedHttpClient,
) -> Result<Vec<UserDto>, ServiceError> {
let users = keycloak_api
.search_users_by_username(search_params, pagination, http_client)
.await
.map_err(|e| {
log::error!("Error getting user data from Keycloak API: {e}");
ServiceError::new(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Error getting user data from Keycloak API: {e}").as_str(),
)
})?;
let filtered_users = users
.iter()
.filter(|user| user.id != user_id)
.cloned()
.collect::<Vec<_>>();
Ok(filtered_users)
}