use std::fmt;
use std::ops::Deref;
use serde::de::DeserializeOwned;
use serde_json::Value;
#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
pub struct Response(Value);
impl Response {
pub(crate) fn new(value: Value) -> Self {
Response(value)
}
pub fn as_value(&self) -> &Value {
&self.0
}
pub fn into_value(self) -> Value {
self.0
}
pub fn deserialize<T: DeserializeOwned>(&self) -> std::result::Result<T, serde_json::Error> {
T::deserialize(&self.0)
}
}
impl Deref for Response {
type Target = Value;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Response {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Clone, Debug)]
pub struct Page {
pub data: Vec<Response>,
pub has_more: bool,
pub next_cursor: Option<String>,
}
impl Page {
pub(crate) fn from_value(value: Value) -> Self {
let data = value
.get("data")
.and_then(Value::as_array)
.map(|items| items.iter().cloned().map(Response::new).collect())
.unwrap_or_default();
let has_more = value
.get("has_more")
.and_then(Value::as_bool)
.unwrap_or(false);
let next_cursor = value
.get("next_cursor")
.and_then(Value::as_str)
.map(str::to_string);
Page {
data,
has_more,
next_cursor,
}
}
}