shared-framework 0.0.17

Reusable building blocks for HTTP services — Hyper routing, SeaORM data layer, validation, OpenAPI docs, jobs, queues, cache.
Documentation
//! Controller result helpers: shortcuts for common success and error outcomes.
//!
//! [`Okay`] builds 200 [`ServiceResult`](crate::response::ServiceResult) values,
//! while the error types build [`ErrorResult`](crate::response::ErrorResult)
//! values with fixed status codes. Return them directly from handlers, whose
//! convention is `Fn(CorrelationContext)` returning
//! `Result<ServiceResult<T>, ErrorResult>`.
//! ```ignore
//! async fn get_user(ctx: CorrelationContext) -> Result<ServiceResult<User>, ErrorResult> {
//!     Ok(Okay::result(user))
//! }
//! ```

use crate::response::{ErrorResult, ServiceResult};

/// Success-result shortcuts: builds 200 `ServiceResult` values for handlers.
pub struct Okay;
impl Okay {
    /// Builds a 200 success result carrying `data` with message `"OK"`.
    pub fn result<T: serde::Serialize>(data: T) -> ServiceResult<T> { ServiceResult::ok("OK", data) }
    /// Builds a 200 success result with no payload and message `"OK"`.
    pub fn empty() -> ServiceResult<()> { ServiceResult::new("success", "OK", None, 200) }
}

/// 401 error shortcut: builds an `ErrorResult` for failed authentication.
pub struct AuthenticationError;
impl AuthenticationError {
    /// Builds a 401 `ErrorResult` with the given message.
    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 401) }
}

/// 403 error shortcut: builds an `ErrorResult` for denied authorization.
pub struct AuthorizationError;
impl AuthorizationError {
    /// Builds a 403 `ErrorResult` with the given message.
    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 403) }
}

/// 500 error shortcut: builds an `ErrorResult` for invalid server configuration.
pub struct BadConfiguration;
impl BadConfiguration {
    /// Builds a 500 `ErrorResult` with the given message.
    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 500) }
}

/// Custom-code error shortcut: builds an `ErrorResult` with a caller-chosen status.
pub struct GenericError;
impl GenericError {
    /// Builds an `ErrorResult` with the given message and HTTP status `code`.
    pub fn new(msg: impl Into<String>, code: u16) -> ErrorResult { ErrorResult::new(msg, None, code) }
}