Added account member API.
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
$kind: collection
|
||||||
|
order: 518
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
$kind: http-request
|
||||||
|
url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003"
|
||||||
|
method: GET
|
||||||
|
settings: {}
|
||||||
|
order: 2000
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
$kind: http-request
|
||||||
|
url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members?limit=20&offset=0"
|
||||||
|
method: GET
|
||||||
|
queryParams:
|
||||||
|
- key: limit
|
||||||
|
value: "20"
|
||||||
|
disabled: false
|
||||||
|
description: ""
|
||||||
|
- key: offset
|
||||||
|
value: "0"
|
||||||
|
disabled: false
|
||||||
|
description: ""
|
||||||
|
settings: {}
|
||||||
|
order: 1000
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
$kind: http-request
|
||||||
|
url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003"
|
||||||
|
method: DELETE
|
||||||
|
settings: {}
|
||||||
|
order: 4000
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
$kind: http-request
|
||||||
|
url: "{{base_url}}/api/accounts/00000000-0000-0000-0003-000000000001/members/00000000-0000-0000-0006-000000000003"
|
||||||
|
method: PUT
|
||||||
|
body:
|
||||||
|
type: json
|
||||||
|
content: |-
|
||||||
|
{
|
||||||
|
"user_id": "00000000-0000-0000-0000-000000000002"
|
||||||
|
}
|
||||||
|
settings: {}
|
||||||
|
order: 3000
|
||||||
+80
@@ -0,0 +1,80 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n INSERT INTO account_members (id, account_id, user_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (id, account_id) DO UPDATE SET\n user_id = EXCLUDED.user_id\n RETURNING WITH (OLD AS old_row, NEW AS new_row)\n old_row.id AS \"old_id?\",\n COALESCE(old_row.account_id, new_row.account_id) AS \"old_account_id!\",\n COALESCE(old_row.user_id, new_row.user_id) AS \"old_user_id!\",\n new_row.id AS \"id!\",\n new_row.account_id AS \"account_id!\",\n new_row.user_id AS \"user_id!\"\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "old_id?",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "old_account_id!",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": "Expression"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "old_user_id!",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": "Expression"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 3,
|
||||||
|
"name": "id!",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 4,
|
||||||
|
"name": "account_id!",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "account_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 5,
|
||||||
|
"name": "user_id!",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "user_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Uuid",
|
||||||
|
"Uuid"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "0782e5945f71e1541ead35a500ce23d6241853c39b99a575b75b3795b54493d9"
|
||||||
|
}
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n SELECT id, account_id, user_id\n FROM account_members\n WHERE account_id = $1\n ORDER BY id\n LIMIT $2\n OFFSET $3\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "account_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "account_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "user_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "user_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Int8",
|
||||||
|
"Int8"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "d4855797f718e952505eff69420fe7884714c2e6f5f10215c38c2a5571bbcd9a"
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n DELETE FROM account_members\n WHERE account_id = $1 AND id = $2\n RETURNING id, account_id, user_id\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "account_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "account_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "user_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "user_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Uuid"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "e2bb42012ebde4620c1a6a3b7802d3b07ea759310f7f20feb9929d87509c4c34"
|
||||||
|
}
|
||||||
+53
@@ -0,0 +1,53 @@
|
|||||||
|
{
|
||||||
|
"db_name": "PostgreSQL",
|
||||||
|
"query": "\n SELECT id, account_id, user_id\n FROM account_members\n WHERE account_id = $1 AND id = $2\n ",
|
||||||
|
"describe": {
|
||||||
|
"columns": [
|
||||||
|
{
|
||||||
|
"ordinal": 0,
|
||||||
|
"name": "id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 1,
|
||||||
|
"name": "account_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "account_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ordinal": 2,
|
||||||
|
"name": "user_id",
|
||||||
|
"type_info": "Uuid",
|
||||||
|
"origin": {
|
||||||
|
"Table": {
|
||||||
|
"table": "account_members",
|
||||||
|
"name": "user_id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"parameters": {
|
||||||
|
"Left": [
|
||||||
|
"Uuid",
|
||||||
|
"Uuid"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"nullable": [
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
false
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hash": "fec880b0ff2fddb5e5a835abed62e7e85e8c7838740a6a41cb50a677c8bcdd11"
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
CREATE TABLE account_members (
|
CREATE TABLE account_members (
|
||||||
|
id UUID DEFAULT gen_random_uuid (),
|
||||||
account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id),
|
account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id),
|
||||||
user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id),
|
user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id),
|
||||||
PRIMARY KEY (account_id, user_id)
|
PRIMARY KEY (id, account_id),
|
||||||
|
CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id)
|
||||||
);
|
);
|
||||||
@@ -50,12 +50,14 @@ VALUES (
|
|||||||
);
|
);
|
||||||
|
|
||||||
INSERT INTO
|
INSERT INTO
|
||||||
account_members (account_id, user_id)
|
account_members (id, account_id, user_id)
|
||||||
VALUES (
|
VALUES (
|
||||||
|
'00000000-0000-0000-0006-000000000001',
|
||||||
'00000000-0000-0000-0003-000000000001',
|
'00000000-0000-0000-0003-000000000001',
|
||||||
'00000000-0000-0000-0000-000000000001'
|
'00000000-0000-0000-0000-000000000001'
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
|
'00000000-0000-0000-0006-000000000002',
|
||||||
'00000000-0000-0000-0003-000000000002',
|
'00000000-0000-0000-0003-000000000002',
|
||||||
'00000000-0000-0000-0000-000000000002'
|
'00000000-0000-0000-0000-000000000002'
|
||||||
);
|
);
|
||||||
|
|||||||
+34
-1
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod account_members;
|
||||||
pub mod accounts;
|
pub mod accounts;
|
||||||
pub mod dtos;
|
pub mod dtos;
|
||||||
mod error_codes;
|
mod error_codes;
|
||||||
@@ -8,7 +9,7 @@ pub mod user_app_secrets;
|
|||||||
pub mod user_apps;
|
pub mod user_apps;
|
||||||
pub mod users;
|
pub mod users;
|
||||||
|
|
||||||
use error_codes::PG_FOREIGN_KEY_VIOLATION;
|
use error_codes::{PG_FOREIGN_KEY_VIOLATION, PG_UNIQUE_VIOLATION};
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
pub enum DatabaseError {
|
pub enum DatabaseError {
|
||||||
@@ -19,6 +20,13 @@ pub enum DatabaseError {
|
|||||||
source: sqlx::Error,
|
source: sqlx::Error,
|
||||||
},
|
},
|
||||||
|
|
||||||
|
#[error("unique violation ({constraint}): {source}")]
|
||||||
|
UniqueViolation {
|
||||||
|
constraint: Constraint,
|
||||||
|
#[source]
|
||||||
|
source: sqlx::Error,
|
||||||
|
},
|
||||||
|
|
||||||
#[error("internal error: {0}")]
|
#[error("internal error: {0}")]
|
||||||
Internal(#[source] sqlx::Error),
|
Internal(#[source] sqlx::Error),
|
||||||
}
|
}
|
||||||
@@ -39,6 +47,19 @@ impl From<sqlx::Error> for DatabaseError {
|
|||||||
source: sqlx::Error::Database(db_err),
|
source: sqlx::Error::Database(db_err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
sqlx::Error::Database(db_err)
|
||||||
|
if db_err.code().as_deref() == Some(PG_UNIQUE_VIOLATION) =>
|
||||||
|
{
|
||||||
|
let constraint = db_err
|
||||||
|
.constraint()
|
||||||
|
.map(Constraint::from)
|
||||||
|
.unwrap_or(Constraint::Unnamed);
|
||||||
|
|
||||||
|
DatabaseError::UniqueViolation {
|
||||||
|
constraint,
|
||||||
|
source: sqlx::Error::Database(db_err),
|
||||||
|
}
|
||||||
|
}
|
||||||
_ => DatabaseError::Internal(err),
|
_ => DatabaseError::Internal(err),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,6 +67,15 @@ impl From<sqlx::Error> for DatabaseError {
|
|||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
pub enum Constraint {
|
pub enum Constraint {
|
||||||
|
#[error("account member account constraint")]
|
||||||
|
AccountMemberAccount,
|
||||||
|
|
||||||
|
#[error("account member account user constraint")]
|
||||||
|
AccountMemberAccountUser,
|
||||||
|
|
||||||
|
#[error("account member user constraint")]
|
||||||
|
AccountMemberUser,
|
||||||
|
|
||||||
#[error("user app user constraint")]
|
#[error("user app user constraint")]
|
||||||
UserAppUser,
|
UserAppUser,
|
||||||
|
|
||||||
@@ -68,6 +98,9 @@ pub enum Constraint {
|
|||||||
impl From<&str> for Constraint {
|
impl From<&str> for Constraint {
|
||||||
fn from(constraint: &str) -> Self {
|
fn from(constraint: &str) -> Self {
|
||||||
match constraint {
|
match constraint {
|
||||||
|
"fk_account_members_account" => Constraint::AccountMemberAccount,
|
||||||
|
"uq_account_members_account_user" => Constraint::AccountMemberAccountUser,
|
||||||
|
"fk_account_members_user" => Constraint::AccountMemberUser,
|
||||||
"fk_user_apps_user" => Constraint::UserAppUser,
|
"fk_user_apps_user" => Constraint::UserAppUser,
|
||||||
"fk_user_app_secrets_app" => Constraint::UserAppSecretApp,
|
"fk_user_app_secrets_app" => Constraint::UserAppSecretApp,
|
||||||
"fk_transactions_account" => Constraint::TransactionAccount,
|
"fk_transactions_account" => Constraint::TransactionAccount,
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
DatabaseError,
|
||||||
|
dtos::{AccountMemberRow, Upsert},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Query {
|
||||||
|
pub account_id: Uuid,
|
||||||
|
pub limit: Option<i64>,
|
||||||
|
pub offset: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<AccountMemberRow>, DatabaseError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
sqlx::query_as!(
|
||||||
|
AccountMemberRow,
|
||||||
|
r#"
|
||||||
|
SELECT id, account_id, user_id
|
||||||
|
FROM account_members
|
||||||
|
WHERE account_id = $1
|
||||||
|
ORDER BY id
|
||||||
|
LIMIT $2
|
||||||
|
OFFSET $3
|
||||||
|
"#,
|
||||||
|
query.account_id,
|
||||||
|
query.limit,
|
||||||
|
query.offset,
|
||||||
|
)
|
||||||
|
.fetch_all(executor)
|
||||||
|
.await
|
||||||
|
.map_err(DatabaseError::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_by_id<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
account_id: Uuid,
|
||||||
|
id: Uuid,
|
||||||
|
) -> Result<Option<AccountMemberRow>, DatabaseError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
sqlx::query_as!(
|
||||||
|
AccountMemberRow,
|
||||||
|
r#"
|
||||||
|
SELECT id, account_id, user_id
|
||||||
|
FROM account_members
|
||||||
|
WHERE account_id = $1 AND id = $2
|
||||||
|
"#,
|
||||||
|
account_id,
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
.fetch_optional(executor)
|
||||||
|
.await
|
||||||
|
.map_err(DatabaseError::from)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upsert<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
member: AccountMemberRow,
|
||||||
|
) -> Result<Upsert<AccountMemberRow>, DatabaseError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let row = sqlx::query!(
|
||||||
|
r#"
|
||||||
|
INSERT INTO account_members (id, account_id, user_id)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
ON CONFLICT (id, account_id) DO UPDATE SET
|
||||||
|
user_id = EXCLUDED.user_id
|
||||||
|
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||||
|
old_row.id AS "old_id?",
|
||||||
|
COALESCE(old_row.account_id, new_row.account_id) AS "old_account_id!",
|
||||||
|
COALESCE(old_row.user_id, new_row.user_id) AS "old_user_id!",
|
||||||
|
new_row.id AS "id!",
|
||||||
|
new_row.account_id AS "account_id!",
|
||||||
|
new_row.user_id AS "user_id!"
|
||||||
|
"#,
|
||||||
|
member.id,
|
||||||
|
member.account_id,
|
||||||
|
member.user_id,
|
||||||
|
)
|
||||||
|
.fetch_one(executor)
|
||||||
|
.await
|
||||||
|
.map_err(DatabaseError::from)?;
|
||||||
|
|
||||||
|
// `old_id` indicates whether there was a previous row before the upsert, other old fields are
|
||||||
|
// coalesced with the new row's values in case there was no previous row. This enables static
|
||||||
|
// typing on the previous row instead of having to check nullability for each old field in code.
|
||||||
|
let previous = row.old_id.map(|id| AccountMemberRow {
|
||||||
|
id,
|
||||||
|
account_id: row.old_account_id,
|
||||||
|
user_id: row.old_user_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Upsert {
|
||||||
|
previous,
|
||||||
|
current: AccountMemberRow {
|
||||||
|
id: row.id,
|
||||||
|
account_id: row.account_id,
|
||||||
|
user_id: row.user_id,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_by_id<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
account_id: Uuid,
|
||||||
|
id: Uuid,
|
||||||
|
) -> Result<Option<AccountMemberRow>, DatabaseError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
sqlx::query_as!(
|
||||||
|
AccountMemberRow,
|
||||||
|
r#"
|
||||||
|
DELETE FROM account_members
|
||||||
|
WHERE account_id = $1 AND id = $2
|
||||||
|
RETURNING id, account_id, user_id
|
||||||
|
"#,
|
||||||
|
account_id,
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
.fetch_optional(executor)
|
||||||
|
.await
|
||||||
|
.map_err(DatabaseError::from)
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
mod account;
|
mod account;
|
||||||
|
mod account_member;
|
||||||
mod recurring_transaction;
|
mod recurring_transaction;
|
||||||
mod results;
|
mod results;
|
||||||
mod token;
|
mod token;
|
||||||
@@ -8,6 +9,7 @@ mod user_app;
|
|||||||
mod user_app_secret;
|
mod user_app_secret;
|
||||||
|
|
||||||
pub use account::*;
|
pub use account::*;
|
||||||
|
pub use account_member::*;
|
||||||
pub use recurring_transaction::*;
|
pub use recurring_transaction::*;
|
||||||
pub use results::*;
|
pub use results::*;
|
||||||
pub use token::*;
|
pub use token::*;
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub struct AccountMemberRow {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub account_id: Uuid,
|
||||||
|
pub user_id: Uuid,
|
||||||
|
}
|
||||||
@@ -1 +1,2 @@
|
|||||||
pub const PG_FOREIGN_KEY_VIOLATION: &str = "23503";
|
pub const PG_FOREIGN_KEY_VIOLATION: &str = "23503";
|
||||||
|
pub const PG_UNIQUE_VIOLATION: &str = "23505";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
mod account;
|
mod account;
|
||||||
|
mod account_member;
|
||||||
mod cents;
|
mod cents;
|
||||||
mod direction;
|
mod direction;
|
||||||
mod recurring_transaction;
|
mod recurring_transaction;
|
||||||
@@ -10,6 +11,7 @@ mod user_app;
|
|||||||
mod user_app_secret;
|
mod user_app_secret;
|
||||||
|
|
||||||
pub use account::*;
|
pub use account::*;
|
||||||
|
pub use account_member::*;
|
||||||
pub use cents::*;
|
pub use cents::*;
|
||||||
pub use direction::*;
|
pub use direction::*;
|
||||||
pub use recurring_transaction::*;
|
pub use recurring_transaction::*;
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct AccountMember {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub account_id: Uuid,
|
||||||
|
pub user_id: Uuid,
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ use crate::{
|
|||||||
domain::{CentsError, ScheduleError, UserAppSecretError},
|
domain::{CentsError, ScheduleError, UserAppSecretError},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub mod account_members;
|
||||||
pub mod accounts;
|
pub mod accounts;
|
||||||
pub mod dtos;
|
pub mod dtos;
|
||||||
mod encoding;
|
mod encoding;
|
||||||
@@ -21,6 +22,13 @@ pub enum RepositoryError {
|
|||||||
#[error(transparent)]
|
#[error(transparent)]
|
||||||
Decode(#[from] DecodeError),
|
Decode(#[from] DecodeError),
|
||||||
|
|
||||||
|
#[error("duplicate ({entity})")]
|
||||||
|
Duplicate {
|
||||||
|
entity: DuplicateEntity,
|
||||||
|
#[source]
|
||||||
|
source: DatabaseError,
|
||||||
|
},
|
||||||
|
|
||||||
#[error("reference violation ({kind}: {relation})")]
|
#[error("reference violation ({kind}: {relation})")]
|
||||||
ReferenceViolation {
|
ReferenceViolation {
|
||||||
relation: ReferenceRelation,
|
relation: ReferenceRelation,
|
||||||
@@ -60,8 +68,17 @@ pub enum DecodeError {
|
|||||||
UserAppSecret(#[from] UserAppSecretError),
|
UserAppSecret(#[from] UserAppSecretError),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum DuplicateEntity {
|
||||||
|
#[error("account member")]
|
||||||
|
AccountMember,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||||
pub enum ReferenceRelation {
|
pub enum ReferenceRelation {
|
||||||
|
#[error("account member")]
|
||||||
|
AccountMember,
|
||||||
|
|
||||||
#[error("account")]
|
#[error("account")]
|
||||||
Account,
|
Account,
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,227 @@
|
|||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
DecodeError, DuplicateEntity, QueryConversionError, ReferenceRelation, ReferenceViolationKind,
|
||||||
|
RepositoryError, dtos::Upsert,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
database::{Constraint, DatabaseError, account_members as db, dtos::AccountMemberRow},
|
||||||
|
domain::AccountMember,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct Query {
|
||||||
|
pub account_id: Uuid,
|
||||||
|
pub limit: Option<u64>,
|
||||||
|
pub offset: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<AccountMember>, RepositoryError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let query = db::Query {
|
||||||
|
account_id: query.account_id,
|
||||||
|
limit: query
|
||||||
|
.limit
|
||||||
|
.map(|limit| i64::try_from(limit).map_err(|_| QueryConversionError::Limit(limit)))
|
||||||
|
.transpose()?,
|
||||||
|
offset: query
|
||||||
|
.offset
|
||||||
|
.map(|offset| i64::try_from(offset).map_err(|_| QueryConversionError::Offset(offset)))
|
||||||
|
.transpose()?,
|
||||||
|
};
|
||||||
|
|
||||||
|
let members = db::list(executor, query)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(decode)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
|
||||||
|
Ok(members)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_by_id<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
account_id: Uuid,
|
||||||
|
id: Uuid,
|
||||||
|
) -> Result<Option<AccountMember>, RepositoryError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let member = db::get_by_id(executor, account_id, id)
|
||||||
|
.await?
|
||||||
|
.map(decode)
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
Ok(member)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upsert<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
member: AccountMember,
|
||||||
|
) -> Result<Upsert<AccountMember>, RepositoryError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let member = db::upsert(executor, encode(member))
|
||||||
|
.await
|
||||||
|
.map_err(classify_upsert_error)?
|
||||||
|
.try_map(decode)?
|
||||||
|
.into();
|
||||||
|
|
||||||
|
Ok(member)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify_upsert_error(error: DatabaseError) -> RepositoryError {
|
||||||
|
match &error {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::AccountMemberAccount,
|
||||||
|
..
|
||||||
|
} => RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::Account,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::AccountMemberUser,
|
||||||
|
..
|
||||||
|
} => RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::User,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
|
DatabaseError::UniqueViolation {
|
||||||
|
constraint: Constraint::AccountMemberAccountUser,
|
||||||
|
..
|
||||||
|
} => RepositoryError::Duplicate {
|
||||||
|
entity: DuplicateEntity::AccountMember,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
|
_ => RepositoryError::Database(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_by_id<'e, E>(
|
||||||
|
executor: E,
|
||||||
|
account_id: Uuid,
|
||||||
|
id: Uuid,
|
||||||
|
) -> Result<Option<AccountMember>, RepositoryError>
|
||||||
|
where
|
||||||
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||||
|
{
|
||||||
|
let member = db::delete_by_id(executor, account_id, id)
|
||||||
|
.await?
|
||||||
|
.map(decode)
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
Ok(member)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(row: AccountMemberRow) -> Result<AccountMember, DecodeError> {
|
||||||
|
Ok(AccountMember {
|
||||||
|
id: row.id,
|
||||||
|
account_id: row.account_id,
|
||||||
|
user_id: row.user_id,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(member: AccountMember) -> AccountMemberRow {
|
||||||
|
AccountMemberRow {
|
||||||
|
id: member.id,
|
||||||
|
account_id: member.account_id,
|
||||||
|
user_id: member.user_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint,
|
||||||
|
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_member_upsert_account_foreign_key_violation() {
|
||||||
|
let error = classify_upsert_error(foreign_key_violation(Constraint::AccountMemberAccount));
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::Account,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_member_upsert_user_foreign_key_violation() {
|
||||||
|
let error = classify_upsert_error(foreign_key_violation(Constraint::AccountMemberUser));
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::User,
|
||||||
|
kind: ReferenceViolationKind::Missing,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_unknown_upsert_foreign_keys_generic() {
|
||||||
|
let error = classify_upsert_error(foreign_key_violation(Constraint::Unnamed));
|
||||||
|
assert!(matches!(error, RepositoryError::Database(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row() -> AccountMemberRow {
|
||||||
|
AccountMemberRow {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
account_id: Uuid::new_v4(),
|
||||||
|
user_id: Uuid::new_v4(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_member_upsert_unique_violation() {
|
||||||
|
let error = classify_upsert_error(DatabaseError::UniqueViolation {
|
||||||
|
constraint: Constraint::AccountMemberAccountUser,
|
||||||
|
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||||
|
});
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RepositoryError::Duplicate {
|
||||||
|
entity: DuplicateEntity::AccountMember,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_unknown_upsert_unique_violations_generic() {
|
||||||
|
let error = classify_upsert_error(DatabaseError::UniqueViolation {
|
||||||
|
constraint: Constraint::Unnamed,
|
||||||
|
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||||
|
});
|
||||||
|
assert!(matches!(error, RepositoryError::Database(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn decodes_valid_rows() {
|
||||||
|
let row = row();
|
||||||
|
let (id, account_id, user_id) = (row.id, row.account_id, row.user_id);
|
||||||
|
let member = decode(row).unwrap();
|
||||||
|
assert_eq!(member.id, id);
|
||||||
|
assert_eq!(member.account_id, account_id);
|
||||||
|
assert_eq!(member.user_id, user_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trips_through_rows() {
|
||||||
|
let member = decode(row()).unwrap();
|
||||||
|
let round_trip = decode(encode(member.clone())).unwrap();
|
||||||
|
assert_eq!(round_trip, member);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,6 +106,14 @@ where
|
|||||||
|
|
||||||
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
||||||
match &error {
|
match &error {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::AccountMemberAccount,
|
||||||
|
..
|
||||||
|
} => RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::AccountMember,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
DatabaseError::ForeignKeyViolation {
|
DatabaseError::ForeignKeyViolation {
|
||||||
constraint: Constraint::TransactionAccount,
|
constraint: Constraint::TransactionAccount,
|
||||||
..
|
..
|
||||||
@@ -153,6 +161,19 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_member_account_delete_foreign_key_constraint() {
|
||||||
|
let error = classify_delete_error(foreign_key_violation(Constraint::AccountMemberAccount));
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::AccountMember,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn classifies_account_delete_foreign_key_constraint() {
|
fn classifies_account_delete_foreign_key_constraint() {
|
||||||
let error = classify_delete_error(foreign_key_violation(
|
let error = classify_delete_error(foreign_key_violation(
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::{DecodeError, QueryConversionError, RepositoryError, dtos::Upsert};
|
use super::{
|
||||||
|
DecodeError, QueryConversionError, ReferenceRelation, ReferenceViolationKind, RepositoryError,
|
||||||
|
dtos::Upsert,
|
||||||
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
database::{DatabaseError, dtos::UserRow, users as db},
|
database::{Constraint, DatabaseError, dtos::UserRow, users as db},
|
||||||
domain::User,
|
domain::User,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -70,7 +73,17 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
||||||
RepositoryError::Database(error)
|
match &error {
|
||||||
|
DatabaseError::ForeignKeyViolation {
|
||||||
|
constraint: Constraint::AccountMemberUser,
|
||||||
|
..
|
||||||
|
} => RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::AccountMember,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
source: error,
|
||||||
|
},
|
||||||
|
_ => RepositoryError::Database(error),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode(row: UserRow) -> Result<User, DecodeError> {
|
fn decode(row: UserRow) -> Result<User, DecodeError> {
|
||||||
@@ -85,8 +98,6 @@ fn encode(user: User) -> UserRow {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::database::Constraint;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||||
@@ -96,6 +107,20 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn classifies_account_member_user_delete_foreign_key_constraint() {
|
||||||
|
let error = classify_delete_error(foreign_key_violation(Constraint::AccountMemberUser));
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RepositoryError::ReferenceViolation {
|
||||||
|
relation: ReferenceRelation::AccountMember,
|
||||||
|
kind: ReferenceViolationKind::StillReferenced,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn keeps_unknown_user_delete_foreign_keys_generic() {
|
fn keeps_unknown_user_delete_foreign_keys_generic() {
|
||||||
let error = classify_delete_error(foreign_key_violation(Constraint::Unnamed));
|
let error = classify_delete_error(foreign_key_violation(Constraint::Unnamed));
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use axum::{http::StatusCode, routing::get};
|
|||||||
|
|
||||||
use crate::error::AppError;
|
use crate::error::AppError;
|
||||||
|
|
||||||
|
mod account_members;
|
||||||
mod accounts;
|
mod accounts;
|
||||||
mod auth_passkey;
|
mod auth_passkey;
|
||||||
mod auth_token;
|
mod auth_token;
|
||||||
@@ -19,6 +20,10 @@ pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
|||||||
.nest("/auth/passkey", auth_passkey::create_router())
|
.nest("/auth/passkey", auth_passkey::create_router())
|
||||||
.nest("/auth/token", auth_token::create_router())
|
.nest("/auth/token", auth_token::create_router())
|
||||||
.nest("/accounts", accounts::create_router())
|
.nest("/accounts", accounts::create_router())
|
||||||
|
.nest(
|
||||||
|
"/accounts/{account_id}/members",
|
||||||
|
account_members::create_router(),
|
||||||
|
)
|
||||||
.nest(
|
.nest(
|
||||||
"/scheduled-transactions",
|
"/scheduled-transactions",
|
||||||
scheduled_transactions::create_router(),
|
scheduled_transactions::create_router(),
|
||||||
|
|||||||
@@ -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;
|
||||||
|
pub mod account_member;
|
||||||
pub mod direction;
|
pub mod direction;
|
||||||
pub mod scheduled_transaction;
|
pub mod scheduled_transaction;
|
||||||
pub mod token;
|
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 {
|
match self {
|
||||||
Self::Database(_) | Self::Decode(_) => internal_error(),
|
Self::Database(_) | Self::Decode(_) => internal_error(),
|
||||||
Self::QueryConversion(error) => (StatusCode::BAD_REQUEST, error.to_string().into()),
|
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, .. } => {
|
Self::ReferenceViolation { relation, kind, .. } => {
|
||||||
use crate::repository::{
|
use crate::repository::{
|
||||||
ReferenceRelation as Relation, ReferenceViolationKind as Kind,
|
ReferenceRelation as Relation, ReferenceViolationKind as Kind,
|
||||||
@@ -112,6 +118,14 @@ impl ClientError for RepositoryError {
|
|||||||
StatusCode::UNPROCESSABLE_ENTITY,
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
"Account cannot be found".into(),
|
"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) => (
|
(Kind::StillReferenced, Relation::RecurringTransaction) => (
|
||||||
StatusCode::CONFLICT,
|
StatusCode::CONFLICT,
|
||||||
"Still referenced by one or more recurring transactions".into(),
|
"Still referenced by one or more recurring transactions".into(),
|
||||||
|
|||||||
Reference in New Issue
Block a user