From 3b5b59ba1c20cc68218dc5c0af18ff7a78f6953d Mon Sep 17 00:00:00 2001 From: kjuulh Date: Sat, 11 Feb 2023 14:02:20 +0100 Subject: [PATCH] unpack response --- crates/dagger-sdk/src/querybuilder.rs | 33 +++++++++++++++++++++++++-- crates/dagger-sdk/tests/mod.rs | 2 +- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/dagger-sdk/src/querybuilder.rs b/crates/dagger-sdk/src/querybuilder.rs index 890fd76..6980abe 100644 --- a/crates/dagger-sdk/src/querybuilder.rs +++ b/crates/dagger-sdk/src/querybuilder.rs @@ -1,7 +1,7 @@ use std::{collections::HashMap, ops::Add, sync::Arc}; +use eyre::Context; use serde::{Deserialize, Serialize}; -use tokio::task::block_in_place; pub fn query() -> Selection { Selection::default() @@ -106,11 +106,13 @@ impl Selection { dbg!(&query); - let resp: Option = match basic.block_on(gql_client.query(&query)) { + let resp: Option = match basic.block_on(gql_client.query(&query)) { Ok(r) => r, Err(e) => eyre::bail!(e), }; + let resp: Option = self.unpack_resp(resp)?; + Ok(resp) } @@ -129,6 +131,33 @@ impl Selection { selections.reverse(); selections } + + pub(crate) fn unpack_resp(&self, resp: Option) -> eyre::Result> + where + D: for<'de> Deserialize<'de>, + { + match resp { + Some(r) => self.unpack_resp_value::(r).map(|v| Some(v)), + None => Ok(None), + } + } + + fn unpack_resp_value(&self, r: serde_json::Value) -> eyre::Result + 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::(r).context("could not deserialize response") + } } #[cfg(test)] diff --git a/crates/dagger-sdk/tests/mod.rs b/crates/dagger-sdk/tests/mod.rs index 581a8b7..9c05397 100644 --- a/crates/dagger-sdk/tests/mod.rs +++ b/crates/dagger-sdk/tests/mod.rs @@ -16,5 +16,5 @@ fn test_example_container() { ) .stdout(); - assert_eq!(out, Some("3.16.2".to_string())) + assert_eq!(out, Some("3.16.2\n".to_string())) }