Prepping account members for enriching user data.
This commit is contained in:
+28
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n\t\tSELECT id\n\t\tFROM users\n\t\tWHERE id = ANY($1)\n\t\t",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "users",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"UuidArray"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "47a30da9fcc527a98f828648ef9948e494d0d25dd2d8b329664e399d8982a3bd"
|
||||||
|
}
|
||||||
@@ -49,6 +49,24 @@ where
|
|||||||
.map_err(DatabaseError::from)
|
.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>
|
pub async fn upsert<'e, E>(executor: E, user: UserRow) -> Result<Upsert<UserRow>, DatabaseError>
|
||||||
where
|
where
|
||||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
|||||||
+6
-3
@@ -17,15 +17,18 @@ pub enum AppError {
|
|||||||
#[error("app id already exists")]
|
#[error("app id already exists")]
|
||||||
AppIdAlreadyExists,
|
AppIdAlreadyExists,
|
||||||
|
|
||||||
|
#[error("cannot remove the last member of an account")]
|
||||||
|
LastAccountMemberRemoval,
|
||||||
|
|
||||||
|
#[error("user id not found")]
|
||||||
|
UserIdNotFound,
|
||||||
|
|
||||||
#[error("invalid client credentials")]
|
#[error("invalid client credentials")]
|
||||||
InvalidClientCredentials,
|
InvalidClientCredentials,
|
||||||
|
|
||||||
#[error("invalid refresh token")]
|
#[error("invalid refresh token")]
|
||||||
InvalidRefreshToken,
|
InvalidRefreshToken,
|
||||||
|
|
||||||
#[error("cannot remove the last member of an account")]
|
|
||||||
LastAccountMemberRemoval,
|
|
||||||
|
|
||||||
#[error("not found")]
|
#[error("not found")]
|
||||||
NotFound,
|
NotFound,
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
@@ -47,6 +49,28 @@ where
|
|||||||
Ok(user)
|
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>
|
pub async fn upsert<'e, E>(executor: E, user: User) -> Result<Upsert<User>, RepositoryError>
|
||||||
where
|
where
|
||||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
use axum::{extract::State, http::StatusCode};
|
use axum::{extract::State, http::StatusCode};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
@@ -8,6 +10,7 @@ use super::{
|
|||||||
extractors::{Auth, Json, Path, Query},
|
extractors::{Auth, Json, Path, Query},
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
|
domain,
|
||||||
error::AppError,
|
error::AppError,
|
||||||
repository::{self, RepositoryError},
|
repository::{self, RepositoryError},
|
||||||
};
|
};
|
||||||
@@ -49,13 +52,15 @@ async fn list_account_members(
|
|||||||
offset: query.offset,
|
offset: query.offset,
|
||||||
};
|
};
|
||||||
|
|
||||||
let members = repository::account_members::list(&pool, user_id, account_id, query)
|
let members = repository::account_members::list(&pool, user_id, account_id, query).await?;
|
||||||
.await?
|
let users = get_users_for_account_members(&pool, &members).await?;
|
||||||
.into_iter()
|
|
||||||
.map(AccountMemberResponse::from)
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
Ok(Json(members))
|
let responses = members
|
||||||
|
.into_iter()
|
||||||
|
.map(|member| create_response(member, &users))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
|
||||||
|
Ok(Json(responses))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[axum::debug_handler]
|
#[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)
|
repository::account_members::get_by_id(&pool, auth.user_id(), account_id, member_id)
|
||||||
.await?
|
.await?
|
||||||
.ok_or(AppError::NotFound)?;
|
.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]
|
#[axum::debug_handler]
|
||||||
@@ -81,8 +87,13 @@ async fn upsert_account_member(
|
|||||||
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
||||||
Json(member): Json<AccountMemberRequest>,
|
Json(member): Json<AccountMemberRequest>,
|
||||||
) -> Result<(StatusCode, Json<AccountMemberResponse>), AppError> {
|
) -> Result<(StatusCode, Json<AccountMemberResponse>), AppError> {
|
||||||
|
let user_id = auth.user_id();
|
||||||
|
|
||||||
let member = member.into_domain(member_id, account_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?
|
.await?
|
||||||
.ok_or(AppError::NotFound)?;
|
.ok_or(AppError::NotFound)?;
|
||||||
|
|
||||||
@@ -92,7 +103,9 @@ async fn upsert_account_member(
|
|||||||
StatusCode::CREATED
|
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]
|
#[axum::debug_handler]
|
||||||
@@ -114,6 +127,7 @@ async fn delete_account_member(
|
|||||||
limit: Some(2),
|
limit: Some(2),
|
||||||
offset: None,
|
offset: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let members =
|
let members =
|
||||||
repository::account_members::list(&mut *tx, user_id, account_id, members_query).await?;
|
repository::account_members::list(&mut *tx, user_id, account_id, members_query).await?;
|
||||||
if let [only] = members.as_slice()
|
if let [only] = members.as_slice()
|
||||||
@@ -131,3 +145,32 @@ async fn delete_account_member(
|
|||||||
|
|
||||||
Ok(StatusCode::NO_CONTENT)
|
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,
|
pub user: UserResponse,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<domain::AccountMember> for AccountMemberResponse {
|
impl AccountMemberResponse {
|
||||||
fn from(member: domain::AccountMember) -> Self {
|
pub fn from_domain(member: domain::AccountMember, user: domain::User) -> Self {
|
||||||
Self {
|
Self {
|
||||||
id: member.id,
|
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]
|
#[test]
|
||||||
fn serializes_account_member_response() {
|
fn serializes_account_member_response() {
|
||||||
let id = Uuid::new_v4();
|
let id = Uuid::new_v4();
|
||||||
let member = request(Uuid::nil())
|
let response = serde_json::to_value(response(id, user())).unwrap();
|
||||||
.into_domain(id, Uuid::new_v4())
|
|
||||||
.unwrap();
|
|
||||||
let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(response["id"], id.to_string());
|
assert_eq!(response["id"], id.to_string());
|
||||||
assert_eq!(response["user"]["id"], Uuid::nil().to_string());
|
assert_eq!(response["user"]["id"], Uuid::nil().to_string());
|
||||||
@@ -72,10 +80,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deserializes_account_member_response_as_request() {
|
fn deserializes_account_member_response_as_request() {
|
||||||
let member = request(Uuid::nil())
|
let response = serde_json::to_value(response(Uuid::new_v4(), user())).unwrap();
|
||||||
.into_domain(Uuid::new_v4(), Uuid::new_v4())
|
|
||||||
.unwrap();
|
|
||||||
let response = serde_json::to_value(AccountMemberResponse::from(member)).unwrap();
|
|
||||||
let request: AccountMemberRequest = serde_json::from_value(response).unwrap();
|
let request: AccountMemberRequest = serde_json::from_value(response).unwrap();
|
||||||
|
|
||||||
assert_eq!(request.user.id, Uuid::nil());
|
assert_eq!(request.user.id, Uuid::nil());
|
||||||
@@ -91,8 +96,8 @@ mod tests {
|
|||||||
assert_eq!(member.account_id, account_id);
|
assert_eq!(member.account_id, account_id);
|
||||||
assert_eq!(member.user_id, user_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.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(),
|
"Scheduled transaction ID already exists".into(),
|
||||||
),
|
),
|
||||||
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App 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 => (
|
Self::InvalidClientCredentials => (
|
||||||
StatusCode::UNAUTHORIZED,
|
StatusCode::UNAUTHORIZED,
|
||||||
"Invalid client credentials".into(),
|
"Invalid client credentials".into(),
|
||||||
),
|
),
|
||||||
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".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::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
|
||||||
Self::Domain(error) => error.client_response(),
|
Self::Domain(error) => error.client_response(),
|
||||||
Self::Extractor(error) => error.client_response(),
|
Self::Extractor(error) => error.client_response(),
|
||||||
|
|||||||
Reference in New Issue
Block a user