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
use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::{
    error::{ApiErrorItem, ApiErrors},
    ty::{ApiModel, ApiTy},
};

// 响应参数
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ApiResponse {
    // 响应头参数
    pub header: Vec<ApiTy>,

    // 内容类型
    pub content_type: Option<String>,

    // 响应体参数
    pub body: Option<ApiTy>,

    // 错误列表
    pub error: HashSet<ApiErrorItem>,
}

pub trait ApiResultExtractor {
    fn api_response(models: &mut HashMap<String, Option<ApiModel>>) -> ApiResponse;

    fn api_error() -> Vec<ApiErrorItem>;
}

impl<T: ApiResultExtractor, E: ApiErrors> ApiResultExtractor for Result<T, E> {
    fn api_response(models: &mut HashMap<String, Option<ApiModel>>) -> ApiResponse {
        T::api_response(models)
    }

    fn api_error() -> Vec<ApiErrorItem> {
        E::api_errors()
    }
}