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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![allow(clippy::assign_op_pattern)]

//!
//! # Response Message
//!
//! Response sent to client. Sends entity name, error code and error message.
//!
use std::fmt::Display;

use fluvio_protocol::{Encoder, Decoder};
use crate::errors::ErrorCode;

use crate::ApiError;

#[derive(Encoder, Decoder, Default, Debug)]
pub struct Status {
    pub name: String,
    pub error_code: ErrorCode,
    pub error_message: Option<String>,
}

impl Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.error_code.is_ok() {
            write!(f, "{}", self.name)
        } else {
            write!(f, "{}: {}", self.name, self.error_code)
        }
    }
}

impl Status {
    pub fn new_ok(name: String) -> Self {
        Self {
            name,
            error_code: ErrorCode::None,
            error_message: None,
        }
    }

    pub fn new(name: String, code: ErrorCode, msg: Option<String>) -> Self {
        Self {
            name,
            error_code: code,
            error_message: msg,
        }
    }

    pub fn is_error(&self) -> bool {
        self.error_code.is_error()
    }

    #[allow(clippy::wrong_self_convention)]
    pub fn as_result(self) -> Result<(), ApiError> {
        if self.error_code.is_ok() {
            Ok(())
        } else {
            Err(ApiError::Code(self.error_code, self.error_message))
        }
    }
}