anycms-core 0.4.2

A unified API response library supporting multiple Rust web frameworks
Documentation
#[cfg(feature = "actix")]
use actix_web::{HttpResponse, Responder};
#[cfg(feature = "actix")]
use serde::Serialize;
#[cfg(feature = "actix")]
use crate::result::{ApiResult, ErrorCode};

#[cfg(feature = "actix")]
fn error_code_to_status(code: ErrorCode) -> actix_web::http::StatusCode {
    match code {
        ErrorCode::Success => actix_web::http::StatusCode::OK,
        ErrorCode::BadRequest => actix_web::http::StatusCode::BAD_REQUEST,
        ErrorCode::Unauthorized => actix_web::http::StatusCode::UNAUTHORIZED,
        ErrorCode::Forbidden => actix_web::http::StatusCode::FORBIDDEN,
        ErrorCode::NotFound => actix_web::http::StatusCode::NOT_FOUND,
        ErrorCode::Conflict => actix_web::http::StatusCode::CONFLICT,
        ErrorCode::TooManyRequests => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
        ErrorCode::ValidationError => actix_web::http::StatusCode::UNPROCESSABLE_ENTITY,
        ErrorCode::InternalError => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
        ErrorCode::NotImplemented => actix_web::http::StatusCode::NOT_IMPLEMENTED,
        ErrorCode::BadGateway => actix_web::http::StatusCode::BAD_GATEWAY,
        ErrorCode::ServiceUnavailable => actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
    }
}

/// Actix-web framework integration for ApiResult
#[cfg(feature = "actix")]
impl<T: Serialize> Responder for ApiResult<T> {
    type Body = actix_web::body::BoxBody;

    fn respond_to(self, _req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
        let status = self
            .code
            .and_then(|code| ErrorCode::from_i32(code))
            .map(error_code_to_status)
            .unwrap_or_else(|| {
                if self.success {
                    actix_web::http::StatusCode::OK
                } else {
                    actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
                }
            });

        HttpResponse::build(status).json(self)
    }
}