unpack response

This commit is contained in:
Kasper Juul Hermansen 2023-02-11 14:02:20 +01:00
parent 99bab8e1b0
commit 3b5b59ba1c
Signed by: kjuulh
GPG Key ID: 0F95C140730F2F23
2 changed files with 32 additions and 3 deletions

View File

@ -1,7 +1,7 @@
use std::{collections::HashMap, ops::Add, sync::Arc}; use std::{collections::HashMap, ops::Add, sync::Arc};
use eyre::Context;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::task::block_in_place;
pub fn query() -> Selection { pub fn query() -> Selection {
Selection::default() Selection::default()
@ -106,11 +106,13 @@ impl Selection {
dbg!(&query); dbg!(&query);
let resp: Option<D> = match basic.block_on(gql_client.query(&query)) { let resp: Option<serde_json::Value> = match basic.block_on(gql_client.query(&query)) {
Ok(r) => r, Ok(r) => r,
Err(e) => eyre::bail!(e), Err(e) => eyre::bail!(e),
}; };
let resp: Option<D> = self.unpack_resp(resp)?;
Ok(resp) Ok(resp)
} }
@ -129,6 +131,33 @@ impl Selection {
selections.reverse(); selections.reverse();
selections selections
} }
pub(crate) fn unpack_resp<D>(&self, resp: Option<serde_json::Value>) -> eyre::Result<Option<D>>
where
D: for<'de> Deserialize<'de>,
{
match resp {
Some(r) => self.unpack_resp_value::<D>(r).map(|v| Some(v)),
None => Ok(None),
}
}
fn unpack_resp_value<D>(&self, r: serde_json::Value) -> eyre::Result<D>
where
D: for<'de> Deserialize<'de>,
{
if let Some(o) = r.as_object() {
let keys = o.keys();
if keys.len() != 1 {
eyre::bail!("too many nested objects inside graphql response")
}
let first = keys.into_iter().next().unwrap();
return self.unpack_resp_value(o.get(first).unwrap().clone());
}
serde_json::from_value::<D>(r).context("could not deserialize response")
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -16,5 +16,5 @@ fn test_example_container() {
) )
.stdout(); .stdout();
assert_eq!(out, Some("3.16.2".to_string())) assert_eq!(out, Some("3.16.2\n".to_string()))
} }