Skip to main content

backbone_integrations/presentation/http/
integration_connector_handler.rs

1//! IntegrationConnector REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14// Backbone framework imports
15use backbone_core::http::BackboneCrudHandler;
16
17// Auth integration (optional)
18#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23// Domain imports
24use crate::domain::entity::*;
25use crate::application::service::{IntegrationConnectorService, ServiceError};
26
27// DTO imports
28use crate::presentation::dto::{CreateIntegrationConnectorDto, UpdateIntegrationConnectorDto, PatchIntegrationConnectorDto, IntegrationConnectorResponseDto};
29
30
31/// Application error type
32#[derive(Debug, thiserror::Error)]
33pub enum IntegrationConnectorError {
34    #[error("Not found: {0}")]
35    NotFound(String),
36    #[error("Validation error: {0}")]
37    Validation(String),
38    #[error("Database error: {0}")]
39    Database(String),
40    #[error("Internal error: {0}")]
41    Internal(String),
42}
43
44impl From<ServiceError> for IntegrationConnectorError {
45    fn from(err: ServiceError) -> Self {
46        match err {
47            ServiceError::NotFound => Self::NotFound(err.to_string()),
48            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
49            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
50            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
51            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
52            ServiceError::Violations(_) => Self::Validation(err.to_string()),
53        }
54    }
55}
56
57impl axum::response::IntoResponse for IntegrationConnectorError {
58    fn into_response(self) -> axum::response::Response {
59        use axum::http::StatusCode;
60        use axum::Json;
61
62        let (status, code) = match &self {
63            Self::NotFound(_) => (StatusCode::NOT_FOUND, "INTEGRATIONCONNECTOR_NOT_FOUND"),
64            Self::Validation(_) => (StatusCode::BAD_REQUEST, "INTEGRATIONCONNECTOR_VALIDATION_ERROR"),
65            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTEGRATIONCONNECTOR_DATABASE_ERROR"),
66            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTEGRATIONCONNECTOR_INTERNAL_ERROR"),
67        };
68
69        let body = serde_json::json!({
70            "success": false,
71            "error": code,
72            "message": self.to_string(),
73        });
74
75        (status, Json(body)).into_response()
76    }
77}
78
79// =============================================================================
80// Route Configuration
81// =============================================================================
82
83/// Create Axum router with all 16 Backbone endpoints for IntegrationConnector.
84///
85/// # Routes
86///
87/// | Method | Path | Description |
88/// |--------|------|-------------|
89/// | GET | /integration_connectors | List with pagination |
90/// | POST | /integration_connectors | Create new |
91/// | GET | /integration_connectors/:id | Get by ID |
92/// | PUT | /integration_connectors/:id | Full update |
93/// | PATCH | /integration_connectors/:id | Partial update |
94/// | DELETE | /integration_connectors/:id | Soft delete |
95/// | POST | /integration_connectors/bulk | Bulk create |
96/// | POST | /integration_connectors/upsert | Upsert |
97/// | GET | /integration_connectors/trash | List deleted |
98/// | POST | /integration_connectors/:id/restore | Restore |
99/// | DELETE | /integration_connectors/empty | Empty trash |
100/// | GET | /integration_connectors/:id/deleted | Get deleted by ID |
101/// | DELETE | /integration_connectors/trash/:id | Permanent delete from trash |
102/// | GET | /integration_connectors/count | Count active entities |
103/// | GET | /integration_connectors/trash/count | Count deleted entities |
104///
105/// # Example
106///
107/// ```text
108/// let service = Arc::new(IntegrationConnectorService::with_repository(repository));
109/// let router = create_integration_connector_routes(service);
110/// ```
111pub fn create_integration_connector_routes(service: Arc<IntegrationConnectorService>) -> Router {
112    BackboneCrudHandler::<IntegrationConnectorService, IntegrationConnector, CreateIntegrationConnectorDto, UpdateIntegrationConnectorDto, IntegrationConnectorResponseDto>::routes(
113        service,
114        "/integration_connectors",
115    )
116}
117
118/// Create Axum router with only the read (GET) endpoints for IntegrationConnector.
119///
120/// Safe for public, unauthenticated exposure (e.g., reference data).
121/// Mutations must be served separately via `create_integration_connector_write_routes`,
122/// typically wrapped in an auth middleware layer.
123pub fn create_integration_connector_read_routes(service: Arc<IntegrationConnectorService>) -> Router {
124    BackboneCrudHandler::<IntegrationConnectorService, IntegrationConnector, CreateIntegrationConnectorDto, UpdateIntegrationConnectorDto, IntegrationConnectorResponseDto>::read_routes(
125        service,
126        "/integration_connectors",
127    )
128}
129
130/// Create Axum router with only the write (mutation) endpoints for IntegrationConnector.
131///
132/// These routes must NOT be publicly exposed. Wrap them with an auth
133/// middleware before nesting into the application router.
134///
135/// # This is unguarded generic CRUD, not a validated write path
136///
137/// These are plain create/update/patch/delete mutations over the entity row —
138/// they bypass all business invariants. If the module exposes a validated write
139/// service (e.g. a command router over its domain engine), serve THAT instead
140/// for any mutation that must respect domain rules.
141pub fn create_integration_connector_write_routes(service: Arc<IntegrationConnectorService>) -> Router {
142    BackboneCrudHandler::<IntegrationConnectorService, IntegrationConnector, CreateIntegrationConnectorDto, UpdateIntegrationConnectorDto, IntegrationConnectorResponseDto>::write_routes(
143        service,
144        "/integration_connectors",
145    )
146}
147
148/// Create authenticated routes with auth middleware.
149///
150/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
151/// is responsible for extracting and validating tokens, then providing
152/// an `AuthContext` via request extensions.
153#[cfg(feature = "auth")]
154pub fn create_protected_integration_connector_routes<A: AuthMiddleware + Send + Sync + 'static>(
155    service: Arc<IntegrationConnectorService>,
156    auth: Arc<A>,
157) -> Router {
158    use axum::middleware;
159    use axum::response::IntoResponse;
160
161    let auth_layer = auth.clone();
162    create_integration_connector_routes(service)
163        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
164            let auth = auth_layer.clone();
165            async move {
166                let token = req.headers()
167                    .get(axum::http::header::AUTHORIZATION)
168                    .and_then(|h| h.to_str().ok())
169                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
170                    .unwrap_or("");
171                match auth.authenticate(token).await {
172                    Ok(ctx) => {
173                        req.extensions_mut().insert(ctx);
174                        next.run(req).await
175                    }
176                    Err(_) => {
177                        (axum::http::StatusCode::UNAUTHORIZED,
178                         axum::Json(serde_json::json!({
179                             "success": false,
180                             "error": "unauthorized",
181                             "message": "Authentication required"
182                         }))
183                        ).into_response()
184                    }
185                }
186            }
187        }))
188}