use reqwest::Method;
use serde_json::json;
use crate::client::{Client, object_or_null, segment};
use crate::error::Result;
use crate::models::Device;
use crate::paging::{ItemStream, ListCall, Page, Paging, filter, paging_setters};
#[derive(Debug, Clone, Copy)]
pub struct Devices<'a> {
client: &'a Client,
}
impl<'a> Devices<'a> {
pub(crate) fn new(client: &'a Client) -> Self {
Devices { client }
}
pub async fn list(&self, params: ListDevices) -> Result<Page<Device>> {
params.call().page(self.client).await
}
pub fn list_all(&self, params: ListDevices) -> ItemStream<Device> {
params.call().walk(self.client)
}
pub async fn get(&self, fingerprint: &str) -> Result<Device> {
let payload = self
.client
.request(Method::GET, &path(fingerprint)?, &[], None)
.await?;
Ok(Device::from_value(object_or_null(payload)))
}
pub async fn update(&self, fingerprint: &str, disregarded: bool) -> Result<Device> {
let path = path(fingerprint)?;
let body = json!({ "disregarded": disregarded });
let payload = self
.client
.request(Method::PATCH, &path, &[], Some(&body))
.await?;
Ok(Device::from_value(object_or_null(payload)))
}
}
#[derive(Debug, Clone, Default)]
pub struct ListDevices {
identity: Option<String>,
term: Option<String>,
paging: Paging,
}
impl ListDevices {
pub fn new() -> Self {
ListDevices::default()
}
pub fn identity(mut self, identity_id: impl Into<String>) -> Self {
self.identity = Some(identity_id.into());
self
}
pub fn term(mut self, term: impl Into<String>) -> Self {
self.term = Some(term.into());
self
}
paging_setters!();
fn call(self) -> ListCall<Device> {
let mut filters = Vec::new();
filter(&mut filters, "identity", self.identity);
filter(&mut filters, "term", self.term);
ListCall {
path: "/devices",
filters,
paging: self.paging,
parse: Device::from_value,
}
}
}
fn path(fingerprint: &str) -> Result<String> {
Ok(format!(
"/devices/{}",
segment(fingerprint, "A device fingerprint")?
))
}