yao-dev-common 0.1.10

Common library
Documentation
use crate::AppError;
use serde::de::DeserializeOwned;
use std::marker::PhantomData;

pub trait ResponseParser<T> {
    fn parse(body: &str) -> Result<T, AppError>;
}

// 为 String 类型实现解析器(直接返回原始内容)
pub struct StringParser;
impl<T: From<String>> ResponseParser<T> for StringParser {
    fn parse(body: &str) -> Result<T, AppError> {
        Ok(body.to_string().into())
    }
}

// 为其他实现了 DeserializeOwned 的类型实现 JSON 解析
pub struct JsonParser<T>(pub PhantomData<T>);
impl<T: DeserializeOwned> ResponseParser<T> for JsonParser<T> {
    fn parse(body: &str) -> Result<T, AppError> {
        serde_json::from_str(body).map_err(|e| e.into())
    }
}