Added account member API.
This commit is contained in:
@@ -0,0 +1,125 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::account_member::{AccountMemberRequest, AccountMemberResponse},
|
||||
extractors::{Auth, Json, Path, Query},
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
repository::{self, RepositoryError},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
.route("/", axum::routing::get(list_account_members))
|
||||
.route(
|
||||
"/{member_id}",
|
||||
axum::routing::get(get_account_member)
|
||||
.put(upsert_account_member)
|
||||
.delete(delete_account_member),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QueryParams {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn list_account_members(
|
||||
Auth(auth): Auth,
|
||||
State(pool): State<PgPool>,
|
||||
Path(account_id): Path<Uuid>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<AccountMemberResponse>>, AppError> {
|
||||
let query = repository::account_members::Query {
|
||||
account_id,
|
||||
limit: Some(query.limit.unwrap_or(20)),
|
||||
offset: query.offset,
|
||||
};
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_account_exists(&mut tx, account_id).await?;
|
||||
let members = repository::account_members::list(&mut *tx, query)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(AccountMemberResponse::from)
|
||||
.collect();
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(members))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_account_member(
|
||||
Auth(auth): Auth,
|
||||
State(pool): State<PgPool>,
|
||||
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<Json<AccountMemberResponse>, AppError> {
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_account_exists(&mut tx, account_id).await?;
|
||||
let member = repository::account_members::get_by_id(&mut *tx, account_id, member_id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
Ok(Json(member.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, member))]
|
||||
async fn upsert_account_member(
|
||||
Auth(auth): Auth,
|
||||
State(pool): State<PgPool>,
|
||||
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
||||
Json(member): Json<AccountMemberRequest>,
|
||||
) -> Result<(StatusCode, Json<AccountMemberResponse>), AppError> {
|
||||
let member = member.into_domain(member_id, account_id)?;
|
||||
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_account_exists(&mut tx, account_id).await?;
|
||||
let upserted = repository::account_members::upsert(&mut *tx, member).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
let status = if upserted.previous.is_some() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::CREATED
|
||||
};
|
||||
|
||||
Ok((status, Json(upserted.current.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn delete_account_member(
|
||||
Auth(auth): Auth,
|
||||
State(pool): State<PgPool>,
|
||||
Path((account_id, member_id)): Path<(Uuid, Uuid)>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let mut tx = pool.begin().await.map_err(RepositoryError::from)?;
|
||||
ensure_account_exists(&mut tx, account_id).await?;
|
||||
let deleted =
|
||||
repository::account_members::delete_by_id(&mut *tx, account_id, member_id).await?;
|
||||
tx.commit().await.map_err(RepositoryError::from)?;
|
||||
|
||||
deleted.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn ensure_account_exists(
|
||||
connection: &mut sqlx::PgConnection,
|
||||
account_id: Uuid,
|
||||
) -> Result<(), AppError> {
|
||||
repository::accounts::get_by_id(&mut *connection, account_id)
|
||||
.await?
|
||||
.map(|_| ())
|
||||
.ok_or(AppError::NotFound)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod account;
|
||||
pub mod account_member;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod token;
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct AccountMemberRequest {
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
impl AccountMemberRequest {
|
||||
pub fn into_domain(
|
||||
self,
|
||||
id: Uuid,
|
||||
account_id: Uuid,
|
||||
) -> Result<domain::AccountMember, domain::DomainError> {
|
||||
Ok(domain::AccountMember {
|
||||
id,
|
||||
account_id,
|
||||
user_id: self.user_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountMemberResponse {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
impl From<domain::AccountMember> for AccountMemberResponse {
|
||||
fn from(member: domain::AccountMember) -> Self {
|
||||
Self {
|
||||
id: member.id,
|
||||
user_id: member.user_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request() -> AccountMemberRequest {
|
||||
AccountMemberRequest {
|
||||
user_id: Uuid::nil(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_account_member_response() {
|
||||
let id = Uuid::new_v4();
|
||||
let member = request().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["user_id"], Uuid::nil().to_string());
|
||||
assert!(response.get("account_id").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_account_member_response_as_request() {
|
||||
let member = request()
|
||||
.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();
|
||||
|
||||
assert_eq!(request.user_id, Uuid::nil());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let account_id = Uuid::new_v4();
|
||||
let user_id = Uuid::new_v4();
|
||||
let member = AccountMemberRequest { user_id }
|
||||
.into_domain(id, account_id)
|
||||
.unwrap();
|
||||
assert_eq!(member.id, id);
|
||||
assert_eq!(member.account_id, account_id);
|
||||
assert_eq!(member.user_id, user_id);
|
||||
|
||||
let response = AccountMemberResponse::from(member);
|
||||
assert_eq!(response.id, id);
|
||||
assert_eq!(response.user_id, user_id);
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,12 @@ impl ClientError for RepositoryError {
|
||||
match self {
|
||||
Self::Database(_) | Self::Decode(_) => internal_error(),
|
||||
Self::QueryConversion(error) => (StatusCode::BAD_REQUEST, error.to_string().into()),
|
||||
Self::Duplicate { entity, .. } => match entity {
|
||||
crate::repository::DuplicateEntity::AccountMember => (
|
||||
StatusCode::CONFLICT,
|
||||
"User is already a member of this account".into(),
|
||||
),
|
||||
},
|
||||
Self::ReferenceViolation { relation, kind, .. } => {
|
||||
use crate::repository::{
|
||||
ReferenceRelation as Relation, ReferenceViolationKind as Kind,
|
||||
@@ -112,6 +118,14 @@ impl ClientError for RepositoryError {
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"Account cannot be found".into(),
|
||||
),
|
||||
(Kind::Missing, Relation::User) => (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"User cannot be found".into(),
|
||||
),
|
||||
(Kind::StillReferenced, Relation::AccountMember) => (
|
||||
StatusCode::CONFLICT,
|
||||
"Still referenced by one or more account members".into(),
|
||||
),
|
||||
(Kind::StillReferenced, Relation::RecurringTransaction) => (
|
||||
StatusCode::CONFLICT,
|
||||
"Still referenced by one or more recurring transactions".into(),
|
||||
|
||||
Reference in New Issue
Block a user