97 lines
2.3 KiB
Rust
97 lines
2.3 KiB
Rust
use axum::{extract::State, http::StatusCode};
|
|
use serde::Deserialize;
|
|
use sqlx::PgPool;
|
|
use uuid::Uuid;
|
|
|
|
use super::{
|
|
dtos::user::{UserRequest, UserResponse},
|
|
extractors::{auth::Auth, json::Json, path::Path, query::Query},
|
|
};
|
|
use crate::{error::AppError, 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>,
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn list_users(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Query(query): Query<QueryParams>,
|
|
) -> Result<Json<Vec<UserResponse>>, AppError> {
|
|
let query = repository::users::Query {
|
|
limit: Some(query.limit.unwrap_or(20)),
|
|
offset: query.offset,
|
|
};
|
|
|
|
let users = repository::users::list(&pool, query)
|
|
.await?
|
|
.into_iter()
|
|
.map(UserResponse::from)
|
|
.collect();
|
|
|
|
Ok(Json(users))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool))]
|
|
async fn get_user(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
) -> Result<Json<UserResponse>, AppError> {
|
|
let user = repository::users::get_by_id(&pool, id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
|
|
Ok(Json(user.into()))
|
|
}
|
|
|
|
#[axum::debug_handler]
|
|
#[tracing::instrument(skip(pool, user))]
|
|
async fn upsert_user(
|
|
Auth(auth): Auth,
|
|
State(pool): State<PgPool>,
|
|
Path(id): Path<Uuid>,
|
|
Json(user): Json<UserRequest>,
|
|
) -> Result<(StatusCode, Json<UserResponse>), AppError> {
|
|
let user = user.into_domain(id)?;
|
|
|
|
let upserted = repository::users::upsert(&pool, user).await?;
|
|
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_user(
|
|
Auth(auth): Auth,
|
|
Path(id): Path<Uuid>,
|
|
State(pool): State<PgPool>,
|
|
) -> Result<StatusCode, AppError> {
|
|
repository::users::delete_by_id(&pool, id)
|
|
.await?
|
|
.ok_or(AppError::NotFound)?;
|
|
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|