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
use super::super::{
    serializable_to_json, try_response_with_state_from_json, NashProtocol, ResponseOrError, State,
};
use crate::errors::Result;
use crate::graphql::list_candles;
use crate::types::{Candle, CandleInterval, DateTimeRange};
use super::super::list_markets::ListMarketsRequest;
use super::super::hooks::{ProtocolHook, NashProtocolRequest};
use async_trait::async_trait;
use tokio::sync::RwLock;
use std::sync::Arc;

/// Get candles associated with market, filtering on several optional fields.
#[derive(Clone, Debug)]
pub struct ListCandlesRequest {
    pub market: String,
    /// page before if using pagination
    pub before: Option<String>,
    pub chronological: Option<bool>,
    /// what kind of candle interval do we want?
    pub interval: Option<CandleInterval>,
    /// max trades to return
    pub limit: Option<i64>,
    /// range of time to get candles
    pub range: Option<DateTimeRange>,
}

/// List of candles as well as an optional link to the next page of data.
#[derive(Debug)]
pub struct ListCandlesResponse {
    pub candles: Vec<Candle>,
    pub next_page: Option<String>,
}

#[async_trait]
impl NashProtocol for ListCandlesRequest {
    type Response = ListCandlesResponse;

    async fn graphql(&self, _state: Arc<RwLock<State>>) -> Result<serde_json::Value> {
        let query = self.make_query();
        let mut serde_value = serializable_to_json(&query)?;
        if self.interval == None {
            // hack to remove interval field if it is null
            let variables = serde_value
                .as_object_mut()
                .unwrap()
                .get_mut("variables")
                .unwrap();
            variables.as_object_mut().unwrap().remove("interval");
        }
        Ok(serde_value)
    }

    async fn response_from_json(
        &self,
        response: serde_json::Value,
        state: Arc<RwLock<State>>
    ) -> Result<ResponseOrError<Self::Response>> {
        try_response_with_state_from_json::<ListCandlesResponse, list_candles::ResponseData>(response, state).await
    }

    async fn run_before(&self, state: Arc<RwLock<State>>) -> Result<Option<Vec<ProtocolHook>>> {
        let state = state.read().await;
        let mut hooks = Vec::new();
        if let None = state.markets {
            hooks.push(ProtocolHook::Protocol(NashProtocolRequest::ListMarkets(
                ListMarketsRequest,
            )))
        }
        Ok(Some(hooks))
    }
}