backbone_catalog/presentation/http/
item_handler.rs1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use rust_decimal::Decimal;
14
15use backbone_core::http::BackboneCrudHandler;
17
18#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24use crate::domain::entity::*;
26use crate::application::service::{ItemService, ServiceError};
27
28use crate::presentation::dto::{CreateItemDto, UpdateItemDto, PatchItemDto, ItemResponseDto};
30
31
32#[derive(Debug, thiserror::Error)]
34pub enum ItemError {
35 #[error("Not found: {0}")]
36 NotFound(String),
37 #[error("Validation error: {0}")]
38 Validation(String),
39 #[error("Database error: {0}")]
40 Database(String),
41 #[error("Internal error: {0}")]
42 Internal(String),
43}
44
45impl From<ServiceError> for ItemError {
46 fn from(err: ServiceError) -> Self {
47 match err {
48 ServiceError::NotFound => Self::NotFound(err.to_string()),
49 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
50 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
51 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
52 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
53 ServiceError::Violations(_) => Self::Validation(err.to_string()),
54 }
55 }
56}
57
58impl axum::response::IntoResponse for ItemError {
59 fn into_response(self) -> axum::response::Response {
60 use axum::http::StatusCode;
61 use axum::Json;
62
63 let (status, code) = match &self {
64 Self::NotFound(_) => (StatusCode::NOT_FOUND, "ITEM_NOT_FOUND"),
65 Self::Validation(_) => (StatusCode::BAD_REQUEST, "ITEM_VALIDATION_ERROR"),
66 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ITEM_DATABASE_ERROR"),
67 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ITEM_INTERNAL_ERROR"),
68 };
69
70 let body = serde_json::json!({
71 "success": false,
72 "error": code,
73 "message": self.to_string(),
74 });
75
76 (status, Json(body)).into_response()
77 }
78}
79
80pub fn create_item_routes(service: Arc<ItemService>) -> Router {
113 BackboneCrudHandler::<ItemService, Item, CreateItemDto, UpdateItemDto, ItemResponseDto>::routes(
114 service,
115 "/items",
116 )
117}
118
119pub fn create_item_read_routes(service: Arc<ItemService>) -> Router {
125 BackboneCrudHandler::<ItemService, Item, CreateItemDto, UpdateItemDto, ItemResponseDto>::read_routes(
126 service,
127 "/items",
128 )
129}
130
131pub fn create_item_write_routes(service: Arc<ItemService>) -> Router {
143 BackboneCrudHandler::<ItemService, Item, CreateItemDto, UpdateItemDto, ItemResponseDto>::write_routes(
144 service,
145 "/items",
146 )
147}
148
149#[cfg(feature = "auth")]
155pub fn create_protected_item_routes<A: AuthMiddleware + Send + Sync + 'static>(
156 service: Arc<ItemService>,
157 auth: Arc<A>,
158) -> Router {
159 use axum::middleware;
160 use axum::response::IntoResponse;
161
162 let auth_layer = auth.clone();
163 create_item_routes(service)
164 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
165 let auth = auth_layer.clone();
166 async move {
167 let token = req.headers()
168 .get(axum::http::header::AUTHORIZATION)
169 .and_then(|h| h.to_str().ok())
170 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
171 .unwrap_or("");
172 match auth.authenticate(token).await {
173 Ok(ctx) => {
174 req.extensions_mut().insert(ctx);
175 next.run(req).await
176 }
177 Err(_) => {
178 (axum::http::StatusCode::UNAUTHORIZED,
179 axum::Json(serde_json::json!({
180 "success": false,
181 "error": "unauthorized",
182 "message": "Authentication required"
183 }))
184 ).into_response()
185 }
186 }
187 }
188 }))
189}