Added initial users API.
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n\t\tSELECT id\n\t\tFROM users\n\t\tWHERE id = $1\n\t\t",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "22d5813be73a45003abd94152c36756917d705c694b36988b1514067d78fa154"
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "DELETE FROM users WHERE id = $1 RETURNING id",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "58327aa90726e98d2f31a5178c611b22b3177ea71f812c9f53e4164f22cd1f8a"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n\t\tSELECT id\n\t\tFROM users\n\t\tORDER BY id DESC\n\t\tLIMIT $1\n\t\tOFFSET $2\n\t\t",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Int8",
|
||||
"Int8"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "87aa6dcbad3e6911c33c93ae02e001ec762ed8877a4a0bc66e195bdb1c113135"
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n\t\tINSERT INTO users (id)\n\t\tVALUES ($1)\n\t\tON CONFLICT (id) DO UPDATE SET\n id = EXCLUDED.id\n\t\tRETURNING WITH (OLD AS old_row, NEW AS new_row)\n\t\t\told_row.id AS \"old_id?\",\n\t\t\tnew_row.id AS \"id!\"\n\t\t",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "old_id?",
|
||||
"type_info": "Uuid"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "id!",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Uuid"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "ee3602e86d747b71e9d7c41965c4c7f58e16790af1303adcfe9686bb35fc741a"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid ()
|
||||
);
|
||||
@@ -1,3 +1,9 @@
|
||||
INSERT INTO
|
||||
users (id)
|
||||
VALUES (
|
||||
'00000000-0000-0000-0000-000000000001'
|
||||
);
|
||||
|
||||
INSERT INTO
|
||||
accounts (id, name)
|
||||
VALUES (
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod dtos;
|
||||
mod error_codes;
|
||||
pub mod recurring_transactions;
|
||||
pub mod transactions;
|
||||
pub mod users;
|
||||
|
||||
use error_codes::PG_FOREIGN_KEY_VIOLATION;
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@ mod account;
|
||||
mod recurring_transaction;
|
||||
mod results;
|
||||
mod transaction;
|
||||
mod user;
|
||||
|
||||
pub use account::*;
|
||||
pub use recurring_transaction::*;
|
||||
pub use results::*;
|
||||
pub use transaction::*;
|
||||
pub use user::*;
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct UserRow {
|
||||
pub id: Uuid,
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DatabaseError,
|
||||
dtos::{Delete, Upsert, UserRow},
|
||||
};
|
||||
|
||||
pub struct Query {
|
||||
pub limit: Option<i64>,
|
||||
pub offset: Option<i64>,
|
||||
}
|
||||
|
||||
impl Default for Query {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
limit: None,
|
||||
offset: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query<'e, E>(executor: E, query: Query) -> Result<Vec<UserRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
UserRow,
|
||||
r#"
|
||||
SELECT id
|
||||
FROM users
|
||||
ORDER BY id DESC
|
||||
LIMIT $1
|
||||
OFFSET $2
|
||||
"#,
|
||||
query.limit,
|
||||
query.offset,
|
||||
)
|
||||
.fetch_all(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
pub async fn get_by_id<'e, E>(executor: E, id: Uuid) -> Result<Option<UserRow>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query_as!(
|
||||
UserRow,
|
||||
r#"
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
"#,
|
||||
id,
|
||||
)
|
||||
.fetch_optional(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>,
|
||||
{
|
||||
let row = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (id)
|
||||
VALUES ($1)
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
id = EXCLUDED.id
|
||||
RETURNING WITH (OLD AS old_row, NEW AS new_row)
|
||||
old_row.id AS "old_id?",
|
||||
new_row.id AS "id!"
|
||||
"#,
|
||||
user.id,
|
||||
)
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
let user = UserRow { id: row.id };
|
||||
|
||||
if row.old_id.is_some() {
|
||||
Ok(Upsert::Updated(user))
|
||||
} else {
|
||||
Ok(Upsert::Created(user))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_by_id<'e, E>(executor: E, id: Uuid) -> Result<Delete, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let deleted = sqlx::query!("DELETE FROM users WHERE id = $1 RETURNING id", id)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(if deleted.is_some() {
|
||||
Delete::Deleted
|
||||
} else {
|
||||
Delete::NotFound
|
||||
})
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod direction;
|
||||
mod recurring_transaction;
|
||||
mod schedule;
|
||||
mod transaction;
|
||||
mod user;
|
||||
|
||||
pub use account::*;
|
||||
pub use cents::*;
|
||||
@@ -11,6 +12,7 @@ pub use direction::*;
|
||||
pub use recurring_transaction::*;
|
||||
pub use schedule::*;
|
||||
pub use transaction::*;
|
||||
pub use user::*;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum DomainError {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
}
|
||||
@@ -8,6 +8,7 @@ pub mod dtos;
|
||||
mod encoding;
|
||||
pub mod recurring_transactions;
|
||||
pub mod transactions;
|
||||
pub mod users;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RepositoryError {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
DecodeError, QueryConversionError, RepositoryError,
|
||||
dtos::{Delete, Upsert},
|
||||
};
|
||||
use crate::{
|
||||
database::{DatabaseError, dtos::UserRow, users as db},
|
||||
domain::User,
|
||||
};
|
||||
|
||||
pub struct Query {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Query {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
limit: None,
|
||||
offset: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Query> for db::Query {
|
||||
type Error = QueryConversionError;
|
||||
|
||||
fn try_from(query: Query) -> Result<Self, Self::Error> {
|
||||
Ok(db::Query {
|
||||
limit: query
|
||||
.limit
|
||||
.map(|l| i64::try_from(l).map_err(|_| QueryConversionError::Limit(l)))
|
||||
.transpose()?,
|
||||
offset: query
|
||||
.offset
|
||||
.map(|o| i64::try_from(o).map_err(|_| QueryConversionError::Offset(o)))
|
||||
.transpose()?,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn list<'e, E>(executor: E, query: Query) -> Result<Vec<User>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let users = db::query(executor, query.try_into()?)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(decode)
|
||||
.collect::<Result<_, DecodeError>>()?;
|
||||
|
||||
Ok(users)
|
||||
}
|
||||
|
||||
pub async fn get<'e, E>(executor: E, id: Uuid) -> Result<Option<User>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let user = db::get_by_id(executor, id).await?.map(decode).transpose()?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
pub async fn upsert<'e, E>(executor: E, user: User) -> Result<Upsert<User>, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let user = db::upsert(executor, encode(user)).await?.try_map(decode)?;
|
||||
|
||||
Ok(user.into())
|
||||
}
|
||||
|
||||
pub async fn delete<'e, E>(executor: E, id: Uuid) -> Result<Delete, RepositoryError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let deleted = db::delete_by_id(executor, id)
|
||||
.await
|
||||
.map_err(classify_delete_error)?;
|
||||
|
||||
Ok(deleted.into())
|
||||
}
|
||||
|
||||
fn classify_delete_error(error: DatabaseError) -> RepositoryError {
|
||||
match &error {
|
||||
_ => RepositoryError::Database(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(row: UserRow) -> Result<User, DecodeError> {
|
||||
Ok(User { id: row.id })
|
||||
}
|
||||
|
||||
fn encode(user: User) -> UserRow {
|
||||
UserRow { id: user.id }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::Constraint;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn foreign_key_violation(constraint: Constraint) -> DatabaseError {
|
||||
DatabaseError::ForeignKeyViolation {
|
||||
constraint,
|
||||
source: sqlx::Error::Protocol("test database cause".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_unknown_user_delete_foreign_keys_generic() {
|
||||
let error = classify_delete_error(foreign_key_violation(Constraint::Unnamed));
|
||||
|
||||
assert!(matches!(error, RepositoryError::Database(_)));
|
||||
}
|
||||
|
||||
fn row() -> UserRow {
|
||||
UserRow { id: Uuid::new_v4() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_valid_rows() {
|
||||
let row = row();
|
||||
let id = row.id;
|
||||
let user = decode(row).unwrap();
|
||||
|
||||
assert_eq!(user.id, id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_rows() {
|
||||
let user = decode(row()).unwrap();
|
||||
assert_eq!(decode(encode(user.clone())).unwrap(), user);
|
||||
}
|
||||
}
|
||||
@@ -7,16 +7,19 @@ pub mod dtos;
|
||||
pub mod extractors;
|
||||
pub mod scheduled_transactions;
|
||||
pub mod transactions;
|
||||
pub mod users;
|
||||
|
||||
pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
|
||||
let accounts = accounts::create_router();
|
||||
let scheduled_transactions = scheduled_transactions::create_router();
|
||||
let transactions = transactions::create_router();
|
||||
let users = users::create_router();
|
||||
|
||||
let api = axum::Router::new()
|
||||
.nest("/accounts", accounts)
|
||||
.nest("/scheduled-transactions", scheduled_transactions)
|
||||
.nest("/transactions", transactions);
|
||||
.nest("/transactions", transactions)
|
||||
.nest("/users", users);
|
||||
|
||||
axum::Router::new()
|
||||
.nest("/api", api)
|
||||
|
||||
@@ -2,3 +2,4 @@ pub mod account;
|
||||
pub mod direction;
|
||||
pub mod scheduled_transaction;
|
||||
pub mod transaction;
|
||||
pub mod user;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UserRequest {}
|
||||
|
||||
impl UserRequest {
|
||||
pub fn into_domain(self, id: Uuid) -> Result<domain::User, domain::DomainError> {
|
||||
Ok(domain::User { id })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct UserResponse {
|
||||
pub id: Uuid,
|
||||
}
|
||||
|
||||
impl From<domain::User> for UserResponse {
|
||||
fn from(user: domain::User) -> Self {
|
||||
Self { id: user.id }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request() -> UserRequest {
|
||||
UserRequest {}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_user_response() {
|
||||
let id = Uuid::nil();
|
||||
let user = request().into_domain(id).unwrap();
|
||||
let response = serde_json::to_value(UserResponse::from(user)).unwrap();
|
||||
|
||||
assert_eq!(response["id"], id.to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_user_response_as_request() {
|
||||
let user = request().into_domain(Uuid::nil()).unwrap();
|
||||
let response = serde_json::to_value(UserResponse::from(user)).unwrap();
|
||||
let _request: UserRequest = serde_json::from_value(response).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_between_dto_and_domain() {
|
||||
let id = Uuid::new_v4();
|
||||
let user = request().into_domain(id).unwrap();
|
||||
assert_eq!(user.id, id);
|
||||
|
||||
let response = UserResponse::from(user);
|
||||
assert_eq!(response.id, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use axum::{extract::State, http::StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
dtos::user::{UserRequest, UserResponse},
|
||||
extractors::{json::Json, path::Path, query::Query},
|
||||
};
|
||||
use crate::{
|
||||
error::AppError,
|
||||
repository::{
|
||||
dtos::{Delete, Upsert},
|
||||
users as repository,
|
||||
},
|
||||
};
|
||||
|
||||
pub fn create_router() -> axum::Router<PgPool> {
|
||||
axum::Router::new()
|
||||
.route("/", axum::routing::get(list_users))
|
||||
.route(
|
||||
"/{id}",
|
||||
axum::routing::get(get_user)
|
||||
.put(upsert_user)
|
||||
.delete(delete_user),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct QueryParams {
|
||||
pub limit: Option<u64>,
|
||||
pub offset: Option<u64>,
|
||||
}
|
||||
|
||||
impl TryFrom<QueryParams> for repository::Query {
|
||||
type Error = AppError;
|
||||
|
||||
fn try_from(query: QueryParams) -> Result<Self, Self::Error> {
|
||||
Ok(repository::Query {
|
||||
limit: Some(query.limit.unwrap_or(20)),
|
||||
offset: query.offset,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn list_users(
|
||||
State(pool): State<PgPool>,
|
||||
Query(query): Query<QueryParams>,
|
||||
) -> Result<Json<Vec<UserResponse>>, AppError> {
|
||||
let users = repository::list(&pool, query.try_into()?)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(UserResponse::from)
|
||||
.collect();
|
||||
|
||||
Ok(Json(users))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn get_user(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<UserResponse>, AppError> {
|
||||
let user = repository::get(&pool, id)
|
||||
.await?
|
||||
.ok_or(AppError::NotFound)?;
|
||||
|
||||
Ok(Json(user.into()))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool, user))]
|
||||
async fn upsert_user(
|
||||
State(pool): State<PgPool>,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(user): Json<UserRequest>,
|
||||
) -> Result<(StatusCode, Json<UserResponse>), AppError> {
|
||||
let user = user.into_domain(id)?;
|
||||
|
||||
let (status, user) = match repository::upsert(&pool, user).await? {
|
||||
Upsert::Created(user) => (StatusCode::CREATED, user),
|
||||
Upsert::Updated(user) => (StatusCode::OK, user),
|
||||
};
|
||||
|
||||
Ok((status, Json(user.into())))
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
#[tracing::instrument(skip(pool))]
|
||||
async fn delete_user(
|
||||
Path(id): Path<Uuid>,
|
||||
State(pool): State<PgPool>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
match repository::delete(&pool, id).await? {
|
||||
Delete::Deleted => Ok(StatusCode::NO_CONTENT),
|
||||
Delete::NotFound => Err(AppError::NotFound),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user