Trait apisdk::JsonExtractor
source · pub trait JsonExtractor {
// Required method
fn try_extract<T>(self) -> ApiResult<T>
where T: DeserializeOwned;
// Provided method
fn require_headers() -> bool { ... }
}
Expand description
This trait is used to extract result from response.
§Usage
let req = client.get("/api/path").await?;
let res = send!(req, TypeOfExtractor).await?;
§Examples
§Check return code
#[derive(serde::Deserialize)]
pub struct CheckReturnCode(serde_json::Value);
impl JsonExtractor for CheckReturnCode {
fn try_extract(self) -> ApiResult<T> {
match self.0.get("ret_code").and_then(|c| c.as_i64()) {
Some(0) => serde_json::from_value(self.0).map_err(|e| e.into()),
Some(c) => Err(ApiError::BusinessError(c, Some("Invalid ret_code".to_string()))),
None => Err(ApiError::BusinessError(-1, Some("No ret_code".to_string()))),
}
}
}
§Extract single field
#[derive(serde::Deserialize)]
pub struct ExtractData {
data: serde_json::Value
}
impl JsonExtractor for ExtractData {
fn try_extract(self) -> ApiResult<T> {
serde_json::from_value(self.data).map_err(|e| e.into())
}
}
§Built-in JsonExtractors
- std::string::String
- treat whole payload as text output
- serde_json::Value
- treat whole payload as json output
- apisdk::WholePayload
- an alias of serde_json::Value
- apisdk::CodeDataMessage
- parse
{code, data, message}
json payload, and returndata
field
- parse
Required Methods§
sourcefn try_extract<T>(self) -> ApiResult<T>where
T: DeserializeOwned,
fn try_extract<T>(self) -> ApiResult<T>where
T: DeserializeOwned,
Try to extract result from response.
The HTTP headers will be inject as __headers__
field if possible.
Provided Methods§
sourcefn require_headers() -> bool
fn require_headers() -> bool
The extractor needs response HTTP headers or not.
Object Safety§
This trait is not object safe.