pub const FACT_BY_ID_INDEXED_QUERY: &str = r#"
query ConfirmIndexed($id: ID!) {
fact(id: $id) {
id
isActive
blockNumber
}
}
"#;
pub const DEFAULT_POLL_INTERVAL_MS: u64 = 1_000;
pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
pub fn confirm_indexed_query() -> &'static str {
FACT_BY_ID_INDEXED_QUERY
}
pub fn parse_indexed_response(response_json: &str) -> Result<bool, String> {
let value: serde_json::Value = serde_json::from_str(response_json).map_err(|e| {
format!(
"confirm_indexed: response is not valid JSON ({}). Body: {}",
e,
response_json.chars().take(200).collect::<String>()
)
})?;
if let Some(data) = value.get("data") {
if data.is_null() {
return Ok(false);
}
if let Some(fact_field) = data.get("fact") {
return Ok(parse_fact_value(fact_field));
}
return Err(
"confirm_indexed: wrapped response missing `fact` field under `data`".to_string(),
);
}
if let Some(fact_field) = value.get("fact") {
return Ok(parse_fact_value(fact_field));
}
Err(format!(
"confirm_indexed: response did not match either {{data:{{fact}}}} or {{fact}} shape: {}",
response_json.chars().take(200).collect::<String>()
))
}
fn parse_fact_value(fact: &serde_json::Value) -> bool {
if fact.is_null() {
return false;
}
fact.get("isActive")
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_wrapped_active_true() {
let r = r#"{"data":{"fact":{"id":"abc","isActive":true,"blockNumber":"123"}}}"#;
assert_eq!(parse_indexed_response(r).unwrap(), true);
}
#[test]
fn parses_wrapped_active_false() {
let r = r#"{"data":{"fact":{"id":"abc","isActive":false,"blockNumber":"123"}}}"#;
assert_eq!(parse_indexed_response(r).unwrap(), false);
}
#[test]
fn parses_wrapped_null_fact() {
let r = r#"{"data":{"fact":null}}"#;
assert_eq!(parse_indexed_response(r).unwrap(), false);
}
#[test]
fn parses_wrapped_null_data() {
let r = r#"{"data":null}"#;
assert_eq!(parse_indexed_response(r).unwrap(), false);
}
#[test]
fn parses_unwrapped_shape() {
let r = r#"{"fact":{"id":"abc","isActive":true,"blockNumber":"123"}}"#;
assert_eq!(parse_indexed_response(r).unwrap(), true);
}
#[test]
fn parses_missing_block_number() {
let r = r#"{"data":{"fact":{"id":"abc","isActive":true}}}"#;
assert_eq!(parse_indexed_response(r).unwrap(), true);
}
#[test]
fn rejects_garbage_input() {
assert!(parse_indexed_response("{not json").is_err());
}
#[test]
fn query_string_contains_fact_isactive() {
let q = confirm_indexed_query();
assert!(q.contains("fact(id: $id)"));
assert!(q.contains("isActive"));
}
}