nle-cloud-sdk 0.1.1

Unofficial asynchronous Rust SDK for the NLECloud (新大陆物联网云平台) IoT platform
Documentation
use crate::error::{Result, SdkError};
use serde::Deserialize;

/// Upstream API response envelope wrapping typed data.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct ApiEnvelope<T> {
    pub status: i32,
    #[allow(dead_code)]
    pub status_code: Option<i32>,
    pub msg: Option<String>,
    pub result_obj: Option<T>,
    #[allow(dead_code)]
    pub error_obj: Option<serde_json::Value>,
}

impl<T> ApiEnvelope<T> {
    /// Unwraps the envelope, mapping logical non-zero status to `SdkError::Api`.
    pub fn into_result(self) -> Result<T> {
        if self.status == 0 {
            self.result_obj.ok_or_else(|| {
                SdkError::UnexpectedResponse(
                    "API reported success but ResultObj was missing from response envelope"
                        .to_string(),
                )
            })
        } else {
            Err(SdkError::Api {
                status: self.status,
                message: self.msg.unwrap_or_else(|| "Unknown API error".to_string()),
            })
        }
    }
}

/// Upstream API response envelope for void/empty operations (e.g. Delete, Put, Commands).
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub(crate) struct EmptyEnvelope {
    pub status: i32,
    #[allow(dead_code)]
    pub status_code: Option<i32>,
    pub msg: Option<String>,
    #[allow(dead_code)]
    pub error_obj: Option<serde_json::Value>,
}

impl EmptyEnvelope {
    /// Unwraps the void envelope, mapping logical non-zero status to `SdkError::Api`.
    pub fn into_result(self) -> Result<()> {
        if self.status == 0 {
            Ok(())
        } else {
            Err(SdkError::Api {
                status: self.status,
                message: self.msg.unwrap_or_else(|| "Unknown API error".to_string()),
            })
        }
    }
}