dryvPacks

@dryv/actix-web-backendv0.1.0

Actix Web handlers with shared serde models and separated async services.

Actix Web BackendBackendUnitPublished 7 days ago2 downloads

dryv pack add @dryv/actix-web-backend
1.1 KBRaw ↗
jinja
use actix_web::{
    HttpResponse, ResponseError,
    http::StatusCode,
};
use serde::Serialize;

#[derive(Debug)]
pub struct ApiError {
    pub status: StatusCode,
    pub message: String,
}

impl ApiError {
    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
        Self { status, message: message.into() }
    }

    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(StatusCode::BAD_REQUEST, message)
    }

    pub fn not_implemented(message: impl Into<String>) -> Self {
        Self::new(StatusCode::NOT_IMPLEMENTED, message)
    }
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

#[derive(Serialize)]
struct ApiErrorBody<'a> {
    message: &'a str,
}

impl ResponseError for ApiError {
    fn status_code(&self) -> StatusCode {
        self.status
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status).json(ApiErrorBody { message: &self.message })
    }
}