1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::fmt::Debug;

use reqwest::{header::HeaderMap, StatusCode, Url};
use serde::Deserialize;
use serde_json::Value;
use uuid::Uuid;

use crate::prelude::*;

#[derive(Debug, PartialEq)]
enum RequestType {
    Rest,
    GraphQL,
}

/// The Response struct represent a server response
#[derive(Debug)]
pub struct Response {
    url: Url,
    response_body: Vec<u8>,
    status_code: StatusCode,
    response_headers: HeaderMap,
    request_id: Uuid,
    request_type: RequestType,
}

impl Response {
    #[doc(hidden)]
    pub fn rest(
        url: Url,
        response_body: Vec<u8>,
        status_code: StatusCode,
        response_headers: HeaderMap,
        request_id: Uuid,
    ) -> Self {
        Self {
            url,
            response_body,
            status_code,
            response_headers,
            request_id,
            request_type: RequestType::Rest,
        }
    }

    #[doc(hidden)]
    pub fn graphql(
        url: Url,
        response_body: Vec<u8>,
        status_code: StatusCode,
        response_headers: HeaderMap,
        request_id: Uuid,
    ) -> Self {
        Self {
            url,
            response_body,
            status_code,
            response_headers,
            request_id,
            request_type: RequestType::GraphQL,
        }
    }

    #[doc(hidden)]
    fn is_graphql(&self) -> bool {
        self.request_type == RequestType::GraphQL
    }

    /// Returns an `HeaderMap` of response headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.response_headers
    }

    /// Returns data from the function.
    pub fn get_data<T>(self, response_extractor: &[&str]) -> PrimaBridgeResult<T>
    where
        for<'de> T: Deserialize<'de> + Debug,
    {
        let json_value = serde_json::from_slice(&self.response_body[..]).map_err(|e| {
            PrimaBridgeError::ResponseBodyNotDeserializable {
                status_code: self.status_code,
                source: e,
            }
        })?;
        let mut selectors = response_extractor.to_vec();
        if self.is_graphql() {
            selectors.insert(0, "data");
        };
        Ok(extract_inner_json(self.url, selectors, json_value)?)
    }

    pub fn raw_body(&self) -> &Vec<u8> {
        &self.response_body
    }

    /// returns `true` if the response is successful
    pub fn is_ok(&self) -> bool {
        self.status_code.is_success()
    }
}

fn extract_inner_json<T>(url: Url, selectors: Vec<&str>, json_value: Value) -> PrimaBridgeResult<T>
where
    for<'de> T: Deserialize<'de> + Debug,
{
    let inner_result =
        selectors
            .into_iter()
            .try_fold(&json_value, |acc: &Value, accessor: &str| {
                acc.get(accessor).ok_or_else(|| {
                    PrimaBridgeError::SelectorNotFound(
                        url.clone(),
                        accessor.to_string(),
                        acc.clone(),
                    )
                })
            })?;
    Ok(serde_json::from_value::<T>(inner_result.clone())?)
}