Skip to main content

anycms_core/frameworks/
actix.rs

1#[cfg(feature = "actix")]
2use actix_web::{HttpResponse, Responder};
3#[cfg(feature = "actix")]
4use serde::Serialize;
5#[cfg(feature = "actix")]
6use crate::result::{ApiResult, ErrorCode};
7
8#[cfg(feature = "actix")]
9fn error_code_to_status(code: ErrorCode) -> actix_web::http::StatusCode {
10    match code {
11        ErrorCode::Success => actix_web::http::StatusCode::OK,
12        ErrorCode::BadRequest => actix_web::http::StatusCode::BAD_REQUEST,
13        ErrorCode::Unauthorized => actix_web::http::StatusCode::UNAUTHORIZED,
14        ErrorCode::Forbidden => actix_web::http::StatusCode::FORBIDDEN,
15        ErrorCode::NotFound => actix_web::http::StatusCode::NOT_FOUND,
16        ErrorCode::Conflict => actix_web::http::StatusCode::CONFLICT,
17        ErrorCode::TooManyRequests => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
18        ErrorCode::ValidationError => actix_web::http::StatusCode::UNPROCESSABLE_ENTITY,
19        ErrorCode::InternalError => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
20        ErrorCode::NotImplemented => actix_web::http::StatusCode::NOT_IMPLEMENTED,
21        ErrorCode::BadGateway => actix_web::http::StatusCode::BAD_GATEWAY,
22        ErrorCode::ServiceUnavailable => actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
23    }
24}
25
26/// Actix-web framework integration for ApiResult
27#[cfg(feature = "actix")]
28impl<T: Serialize> Responder for ApiResult<T> {
29    type Body = actix_web::body::BoxBody;
30
31    fn respond_to(self, _req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
32        let status = self
33            .code
34            .and_then(|code| ErrorCode::from_i32(code))
35            .map(error_code_to_status)
36            .unwrap_or_else(|| {
37                if self.success {
38                    actix_web::http::StatusCode::OK
39                } else {
40                    actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
41                }
42            });
43
44        HttpResponse::build(status).json(self)
45    }
46}