Prepping account members for enriching user data.
This commit is contained in:
@@ -49,6 +49,24 @@ where
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(executor: E, ids: &[Uuid]) -> Result<Vec<UserRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
UserRow,
|
||||
r#"
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE id = ANY($1)
|
||||
"#,
|
||||
ids,
|
||||
)
|
||||
.fetch_all(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(executor: E, user: UserRow) -> Result<Upsert<UserRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
|
||||
+6
-3
@@ -17,15 +17,18 @@ pub enum AppError {
|
||||
#[error("app id already exists")]
|
||||
AppIdAlreadyExists,
|
||||
|
||||
#[error("cannot remove the last member of an account")]
|
||||
LastAccountMemberRemoval,
|
||||
|
||||
#[error("user id not found")]
|
||||
UserIdNotFound,
|
||||
|
||||
#[error("invalid client credentials")]
|
||||
InvalidClientCredentials,
|
||||
|
||||
#[error("invalid refresh token")]
|
||||
InvalidRefreshToken,
|
||||
|
||||
#[error("cannot remove the last member of an account")]
|
||||
LastAccountMemberRemoval,
|
||||
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
@@ -47,6 +49,28 @@ where
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
pub async fn get_by_ids<'e, E>(
|
||||
executor: E,
|
||||
ids: &[Uuid],
|
||||
) -> Result<HashMap<Uuid, User>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
if ids.is_empty() {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
|
||||
let users = db::get_by_ids(executor, ids)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let user_map = users.into_iter().map(|user| (user.id, user)).collect();
|
||||
|
||||
Ok(user_map)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(executor: E, user: User) -> Result<Upsert<User>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
@@ -8,6 +10,7 @@ use super::{
|
||||
extractors::{Auth, Json, Path, Query},
|
||||
};
|
||||
use crate::{
|
||||
domain,
|
||||
error::AppError,
|
||||
repository::{self, RepositoryError},
|
||||
};
|
||||
@@ -49,13 +52,15 @@ async fn list_account_members(
|
||||
offset: query.offset,
|
||||
};
|
||||
|
||||
let members = repository::account_members::list(&pool, user_id, account_id, query)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(AccountMemberResponse::from)
|
||||
.collect();
|
||||
let members = repository::account_members::list(&pool, user_id, account_id, query).await?;
|
||||
let users = get_users_for_account_members(&pool, &members).await?;
|
||||
|
||||
Ok(Json(members))
|
||||
let responses = members
|
||||
.into_iter()
|
||||
.map(|member| create_response(member, &users))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -69,8 +74,9 @@ async fn get_account_member(
|
||||
repository::account_members::get_by_id(&pool, auth.user_id(), account_id, member_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
let users = get_users_for_account_members(&pool, std::slice::from_ref(&member)).await?;
|
||||
|
||||
Ok(Json(member.into()))
|
||||
Ok(Json(create_response(member, &users)?))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -81,8 +87,13 @@ async fn upsert_account_member(
|
||||
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
||||
Json(member): Json<AccountMemberRequest>,
|
||||
) -> Result<(StatusCode, Json<AccountMemberResponse>), AppError> {
|
||||
let user_id = auth.user_id();
|
||||
|
||||
let member = member.into_domain(member_id, account_id)?;
|
||||
let upserted = repository::account_members::upsert(&pool, auth.user_id(), member)
|
||||
let user = repository::users::get_by_id(&pool, member.user_id)
|
||||
.await?
|
||||
.ok_or(AppError::UserIdNotFound)?;
|
||||
let upserted = repository::account_members::upsert(&pool, user_id, member)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
@@ -92,7 +103,9 @@ async fn upsert_account_member(
|
||||
StatusCode::CREATED
|
||||
};
|
||||
|
||||
Ok((status, Json(upserted.current.into())))
|
||||
let users = HashMap::from([(user.id, user)]);
|
||||
|
||||
Ok((status, Json(create_response(upserted.current, &users)?)))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
@@ -114,6 +127,7 @@ async fn delete_account_member(
|
||||
limit: Some(2),
|
||||
offset: None,
|
||||
};
|
||||
|
||||
let members =
|
||||
repository::account_members::list(&mut *tx, user_id, account_id, members_query).await?;
|
||||
if let [only] = members.as_slice()
|
||||
@@ -131,3 +145,32 @@ async fn delete_account_member(
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn get_users_for_account_members<'e, E>(
|
||||
executor: E,
|
||||
account_members: &[domain::AccountMember],
|
||||
) -> Result<HashMap<Uuid, domain::User>, AppError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let user_ids = account_members
|
||||
.iter()
|
||||
.map(|account_member| account_member.user_id)
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(repository::users::get_by_ids(executor, &user_ids).await?)
|
||||
}
|
||||
|
||||
fn create_response(
|
||||
account_member: domain::AccountMember,
|
||||
users: &HashMap<Uuid, domain::User>,
|
||||
) -> Result<AccountMemberResponse, AppError> {
|
||||
let user = users
|
||||
.get(&account_member.user_id)
|
||||
.cloned()
|
||||
.ok_or(AppError::Unknown)?;
|
||||
|
||||
Ok(AccountMemberResponse::from_domain(account_member, user))
|
||||
}
|
||||
|
||||
@@ -33,11 +33,11 @@ pub struct AccountMemberResponse {
|
||||
pub user: UserResponse,
|
||||
}
|
||||
|
||||
impl From<domain::AccountMember> for AccountMemberResponse {
|
||||
fn from(member: domain::AccountMember) -> Self {
|
||||
impl AccountMemberResponse {
|
||||
pub fn from_domain(member: domain::AccountMember, user: domain::User) -> Self {
|
||||
Self {
|
||||
id: member.id,
|
||||
user: UserResponse { id: member.user_id },
|
||||
user: UserResponse { id: user.id },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,13 +57,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn response(id: Uuid, user: domain::User) -> AccountMemberResponse {
|
||||
AccountMemberResponse {
|
||||
id,
|
||||
user: UserResponse { id: user.id },
|
||||
}
|
||||
}
|
||||
|
||||
fn user() -> domain::User {
|
||||
domain::User { id: Uuid::nil() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_account_member_response() {
|
||||
let id = Uuid::new_v4();
|
||||
let member = request(Uuid::nil())
|
||||
.into_domain(id, Uuid::new_v4())
|
||||
.unwrap();
|
||||
let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap();
|
||||
let response = serde_json::to_value(response(id, user())).unwrap();
|
||||
|
||||
assert_eq!(response["id"], id.to_string());
|
||||
assert_eq!(response["user"]["id"], Uuid::nil().to_string());
|
||||
@@ -72,10 +80,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn deserializes_account_member_response_as_request() {
|
||||
let member = request(Uuid::nil())
|
||||
.into_domain(Uuid::new_v4(), Uuid::new_v4())
|
||||
.unwrap();
|
||||
let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap();
|
||||
let response = serde_json::to_value(response(Uuid::new_v4(), user())).unwrap();
|
||||
let request: AccountMemberRequest = serde_json::from_value(response).unwrap();
|
||||
|
||||
assert_eq!(request.user.id, Uuid::nil());
|
||||
@@ -91,8 +96,8 @@ mod tests {
|
||||
assert_eq!(member.account_id, account_id);
|
||||
assert_eq!(member.user_id, user_id);
|
||||
|
||||
let response = AccountMemberResponse::from(member);
|
||||
let response = response(id, user());
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.user.id, user_id);
|
||||
assert_eq!(response.user.id, Uuid::nil());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,15 +40,19 @@ impl ClientError for AppError {
|
||||
"Scheduled transaction ID already exists".into(),
|
||||
),
|
||||
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App ID already exists".into()),
|
||||
Self::LastAccountMemberRemoval => (
|
||||
StatusCode::CONFLICT,
|
||||
"Cannot remove the last member of an account".into(),
|
||||
),
|
||||
Self::UserIdNotFound => (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"User ID cannot be found".into(),
|
||||
),
|
||||
Self::InvalidClientCredentials => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid client credentials".into(),
|
||||
),
|
||||
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".into()),
|
||||
Self::LastAccountMemberRemoval => (
|
||||
StatusCode::CONFLICT,
|
||||
"Cannot remove the last member of an account".into(),
|
||||
),
|
||||
Self::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
|
||||
Self::Domain(error) => error.client_response(),
|
||||
Self::Extractor(error) => error.client_response(),
|
||||
|
||||
Reference in New Issue
Block a user