utils.rs (2133B)
1 //! Utility functions for common operations across handlers 2 //! 3 //! This module provides helper functions to reduce code duplication 4 //! and maintain consistency across API handlers. 5 6 use axum::{ 7 http::StatusCode, 8 response::{IntoResponse, Response}, 9 Json, 10 }; 11 12 /// Calculate pagination parameters with defaults and constraints 13 /// 14 /// # Arguments 15 /// * `page` - Optional page number (defaults to 1, minimum 1) 16 /// * `page_size` - Optional page size (defaults to 20, clamped between 1-100) 17 /// 18 /// # Returns 19 /// Tuple of (page, page_size, offset) 20 pub fn calculate_pagination(page: Option<i32>, page_size: Option<i32>) -> (i32, i32, i32) { 21 let page = page.unwrap_or(1).max(1); 22 let page_size = page_size.unwrap_or(20).clamp(1, 100); 23 let offset = (page - 1) * page_size; 24 (page, page_size, offset) 25 } 26 27 /// Calculate total pages from total count and page size 28 /// 29 /// # Arguments 30 /// * `total_count` - Total number of items 31 /// * `page_size` - Number of items per page 32 /// 33 /// # Returns 34 /// Total number of pages (rounded up) 35 pub fn calculate_total_pages(total_count: i64, page_size: i32) -> i32 { 36 ((total_count as f64) / (page_size as f64)).ceil() as i32 37 } 38 39 /// Create an internal server error response 40 /// 41 /// # Arguments 42 /// * `message` - User-facing error message 43 /// * `details` - Technical error details (from database, etc.) 44 /// 45 /// # Returns 46 /// Response with 500 status code 47 pub fn internal_error(message: &str, details: String) -> Response { 48 ( 49 StatusCode::INTERNAL_SERVER_ERROR, 50 Json(serde_json::json!({ 51 "error": message, 52 "details": details 53 })), 54 ) 55 .into_response() 56 } 57 58 /// Create a not found error response 59 /// 60 /// # Arguments 61 /// * `message` - Error message 62 /// * `details` - Additional details (e.g., UUID that wasn't found) 63 /// 64 /// # Returns 65 /// Response with 404 status code 66 pub fn not_found_error(message: &str, details: serde_json::Value) -> Response { 67 ( 68 StatusCode::NOT_FOUND, 69 Json(serde_json::json!({ 70 "error": message, 71 "details": details 72 })), 73 ) 74 .into_response() 75 }