~starkingdoms/starkingdoms

ref: 3f9784408f5c43e366106d0f547d80d9b33ffa37 starkingdoms/starkingdoms-api/src/response.rs -rw-r--r-- 1.4 KiB
3f978440 — ghostlyzsh attaching and despawning modules works 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use crate::error::APIErrorResponse;
use actix_web::body::BoxBody;
use actix_web::error::JsonPayloadError;
use actix_web::http::StatusCode;
use actix_web::{HttpRequest, HttpResponse, Responder};
use serde::Serialize;
use std::fmt::{Debug, Display, Formatter};

#[derive(Debug)]
pub enum JsonAPIResponse<T: Serialize + Debug> {
    Error(StatusCode, APIErrorResponse),
    Success(StatusCode, SuccessResponse<T>),
}

#[derive(Serialize, Debug)]
pub struct SuccessResponse<T: Serialize + Debug> {
    pub success: bool,
    pub data: T,
}

impl<T: Serialize + Debug> Display for JsonAPIResponse<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

// Transparent pass-through to Json()
impl<T: Serialize + Debug> Responder for JsonAPIResponse<T> {
    type Body = BoxBody;

    fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> {
        match self {
            JsonAPIResponse::Error(c, r) => match serde_json::to_string(&r) {
                Ok(body) => HttpResponse::build(c).body(body),
                Err(err) => HttpResponse::from_error(JsonPayloadError::Serialize(err)),
            },
            JsonAPIResponse::Success(c, b) => match serde_json::to_string(&b) {
                Ok(body) => HttpResponse::build(c).body(body),
                Err(err) => HttpResponse::from_error(JsonPayloadError::Serialize(err)),
            },
        }
    }
}