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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
#[cfg(feature = "async")]
use crate::types::response::QueryAsyncResponse;
#[cfg(not(feature = "async"))]
use crate::types::response::QueryResponse;
use crate::types::{
    error::CruxError,
    http::{Action, Order},
    query::Query,
    response::{EntityHistoryResponse, EntityTxResponse, TxLogResponse, TxLogsResponse},
};
use chrono::prelude::*;
use edn_rs::{edn, Edn, Map, Serialize};
#[cfg(not(feature = "async"))]
use reqwest::blocking;
use reqwest::header::HeaderMap;
use std::collections::BTreeSet;
use std::str::FromStr;

static DATE_FORMAT: &'static str = "%Y-%m-%dT%H:%M:%S%Z";

/// `HttpClient` has the `reqwest::blocking::Client`,  the `uri` to query and the `HeaderMap` with
/// all the possible headers. Default header is `Content-Type: "application/edn"`. Synchronous request.
pub struct HttpClient {
    #[cfg(not(feature = "async"))]
    pub(crate) client: blocking::Client,
    #[cfg(feature = "async")]
    pub(crate) client: reqwest::Client,
    pub(crate) uri: String,
    pub(crate) headers: HeaderMap,
}

#[cfg(not(feature = "async"))]
impl HttpClient {
    /// Function `tx_log` requests endpoint `/tx-log` via `POST` which allow you to send actions `Action`
    /// to CruxDB.
    /// The "write" endpoint, to post transactions.
    pub fn tx_log(&self, actions: Vec<Action>) -> Result<TxLogResponse, CruxError> {
        let actions_str = actions
            .into_iter()
            .map(|edn| edn.serialize())
            .collect::<Vec<String>>()
            .join(", ");
        let mut s = String::new();
        s.push_str("[");
        s.push_str(&actions_str);
        s.push_str("]");

        let resp = self
            .client
            .post(&format!("{}/tx-log", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()?
            .text()?;

        let clean_resp = resp.replace("#inst", "");
        edn_rs::from_str(&clean_resp).map_err(|e| e.into())
    }

    /// Function `tx_logs` requests endpoint `/tx-log` via `GET` and returns a list of all transactions
    pub fn tx_logs(&self) -> Result<TxLogsResponse, CruxError> {
        let resp = self
            .client
            .get(&format!("{}/tx-log", self.uri))
            .headers(self.headers.clone())
            .send()?
            .text()?;
        TxLogsResponse::from_str(&resp)
    }

    /// Function `entity` requests endpoint `/entity` via `POST` which retrieves the last document
    /// in CruxDB.
    /// Field with `CruxId` is required.
    /// Response is a `reqwest::Result<edn_rs::Edn>` with the last Entity with that ID.
    pub fn entity(&self, id: String) -> Result<Edn, CruxError> {
        if !id.starts_with(":") {
            return Ok(edn!({:status ":bad-request", :message "ID required", :code 400}));
        }

        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let resp = self
            .client
            .post(&format!("{}/entity", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()?
            .text()?;

        let edn_resp = Edn::from_str(&resp.replace("#inst", ""));
        edn_resp.or(Ok(edn!({:status ":internal-server-error", :code 500})))
    }

    /// Function `entity_timed` is like `entity` but with two optional fields `transaction_time` and `valid_time` that are of type `Option<DateTime<FixedOffset>>`.
    pub fn entity_timed(
        &self,
        id: String,
        transaction_time: Option<DateTime<FixedOffset>>,
        valid_time: Option<DateTime<FixedOffset>>,
    ) -> Result<Edn, CruxError> {
        if !id.starts_with(":") {
            return Ok(edn!({:status ":bad-request", :message "ID required", :code 400}));
        }

        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let url = build_timed_url(self.uri.clone(), "entity", transaction_time, valid_time);

        let resp = self
            .client
            .post(&url)
            .headers(self.headers.clone())
            .body(s)
            .send()?
            .text()?;

        let edn_resp = Edn::from_str(&resp.replace("#inst", ""));
        edn_resp.or(Ok(edn!({:status ":internal-server-error", :code 500})))
    }

    /// Function `entity_tx` requests endpoint `/entity-tx` via `POST` which retrieves the docs and tx infos
    /// for the last document for that ID saved in CruxDB.
    pub fn entity_tx(&self, id: String) -> Result<EntityTxResponse, CruxError> {
        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let resp = self
            .client
            .post(&format!("{}/entity-tx", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()?
            .text()?;

        EntityTxResponse::from_str(&resp.replace("#inst", ""))
    }

    /// Function `entity_tx_timed` is like `entity_tx` but with two optional fields `transaction_time` and `valid_time` that are of type `Option<DateTime<FixedOffset>>`.
    pub fn entity_tx_timed(
        &self,
        id: String,
        transaction_time: Option<DateTime<FixedOffset>>,
        valid_time: Option<DateTime<FixedOffset>>,
    ) -> Result<EntityTxResponse, CruxError> {
        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let url = build_timed_url(self.uri.clone(), "entity-tx", transaction_time, valid_time);

        let resp = self
            .client
            .post(&url)
            .headers(self.headers.clone())
            .body(s)
            .send()?
            .text()?;

        EntityTxResponse::from_str(&resp.replace("#inst", ""))
    }

    /// Function `entity_history` requests endpoint `/entity-history` via `GET` which returns a list with all entity's transaction history.
    /// It is possible to order it with [`Order`](../types/http/enum.Order.html) , `types::http::Order::Asc` and `types::http::Order:Desc`, (second argument) and to include the document for each transaction with the boolean flag `with_docs` (third argument).
    pub fn entity_history(
        &self,
        hash: String,
        order: Order,
        with_docs: bool,
    ) -> Result<EntityHistoryResponse, CruxError> {
        let url = format!(
            "{}/entity-history/{}?sort-order={}&with-docs={}",
            self.uri,
            hash,
            order.serialize(),
            with_docs
        );
        let resp = self
            .client
            .get(&url)
            .headers(self.headers.clone())
            .send()?
            .text()?;

        EntityHistoryResponse::from_str(&resp.replace("#inst", ""))
    }

    /// Function `entity_history_timed` is an txtension of the function `entity_history`.
    /// This function receives as the last argument a vector containing [`TimeHistory`](../types/http/enum.TimeHistory.html)  elements.
    /// `TimeHistory` can be `ValidTime` or `TransactionTime` and both have optional `DateTime<Utc>` params corresponding to the start-time and end-time to be queried.
    pub fn entity_history_timed(
        &self,
        hash: String,
        order: Order,
        with_docs: bool,
        time: Vec<crate::types::http::TimeHistory>,
    ) -> Result<EntityHistoryResponse, CruxError> {
        let url = format!(
            "{}/entity-history/{}?sort-order={}&with-docs={}{}",
            self.uri,
            hash,
            order.serialize(),
            with_docs,
            time.serialize().replace("[", "").replace("]", ""),
        );

        let resp = self
            .client
            .get(&url)
            .headers(self.headers.clone())
            .send()?
            .text()?;

        EntityHistoryResponse::from_str(&resp.replace("#inst", ""))
    }

    /// Function `query` requests endpoint `/query` via `POST` which retrives a Set containing a vector of the values defined by the function [`Query::find` - github example](https://github.com/naomijub/transistor/blob/master/examples/simple_query.rs#L53).
    /// Argument is a `query` of the type `Query`.
    pub fn query(&self, query: Query) -> Result<BTreeSet<Vec<String>>, CruxError> {
        let resp = self
            .client
            .post(&format!("{}/query", self.uri))
            .headers(self.headers.clone())
            .body(query.serialize())
            .send()?
            .text()?;

        let query_response: QueryResponse = edn_rs::from_str(&resp)?;

        Ok(query_response.0)
    }
}

#[cfg(feature = "async")]
impl HttpClient {
    pub async fn tx_log(&self, actions: Vec<Action>) -> Result<TxLogResponse, CruxError> {
        let actions_str = actions
            .into_iter()
            .map(|edn| edn.serialize())
            .collect::<Vec<String>>()
            .join(", ");
        let mut s = String::new();
        s.push_str("[");
        s.push_str(&actions_str);
        s.push_str("]");

        let resp = self
            .client
            .post(&format!("{}/tx-log", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()
            .await?
            .text()
            .await?;

        edn_rs::from_str(&resp).map_err(|e| e.into())
    }

    pub async fn tx_logs(&self) -> Result<TxLogsResponse, CruxError> {
        let resp = self
            .client
            .get(&format!("{}/tx-log", self.uri))
            .headers(self.headers.clone())
            .send()
            .await?
            .text()
            .await?;

        TxLogsResponse::from_str(&resp)
    }

    pub async fn entity(&self, id: String) -> Result<Edn, CruxError> {
        if !id.starts_with(":") {
            return Ok(edn!({:status ":bad-request", :message "ID required", :code 400}));
        }

        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let resp = self
            .client
            .post(&format!("{}/entity", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()
            .await?
            .text()
            .await?;

        let edn_resp = Edn::from_str(&resp.replace("#inst", ""));
        edn_resp.or(Ok(edn!({:status ":internal-server-error", :code 500})))
    }

    pub async fn entity_timed(
        &self,
        id: String,
        transaction_time: Option<DateTime<FixedOffset>>,
        valid_time: Option<DateTime<FixedOffset>>,
    ) -> Result<Edn, CruxError> {
        if !id.starts_with(":") {
            return Ok(edn!({:status ":bad-request", :message "ID required", :code 400}));
        }

        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let url = build_timed_url(self.uri.clone(), "entity", transaction_time, valid_time);
        let resp = self
            .client
            .post(&url)
            .headers(self.headers.clone())
            .body(s)
            .send()
            .await?
            .text()
            .await?;

        let edn_resp = Edn::from_str(&resp.replace("#inst", ""));
        edn_resp.or(Ok(edn!({:status ":internal-server-error", :code 500})))
    }

    pub async fn entity_tx(&self, id: String) -> Result<EntityTxResponse, CruxError> {
        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let resp = self
            .client
            .post(&format!("{}/entity-tx", self.uri))
            .headers(self.headers.clone())
            .body(s)
            .send()
            .await?
            .text()
            .await?;

        EntityTxResponse::from_str(&resp.replace("#inst", ""))
    }

    pub async fn entity_tx_timed(
        &self,
        id: String,
        transaction_time: Option<DateTime<FixedOffset>>,
        valid_time: Option<DateTime<FixedOffset>>,
    ) -> Result<EntityTxResponse, CruxError> {
        let mut s = String::new();
        s.push_str("{:eid ");
        s.push_str(&id);
        s.push_str("}");

        let url = build_timed_url(self.uri.clone(), "entity-tx", transaction_time, valid_time);

        let resp = self
            .client
            .post(&url)
            .headers(self.headers.clone())
            .body(s)
            .send()
            .await?
            .text()
            .await?;

        EntityTxResponse::from_str(&resp.replace("#inst", ""))
    }

    pub async fn entity_history(
        &self,
        hash: String,
        order: Order,
        with_docs: bool,
    ) -> Result<EntityHistoryResponse, CruxError> {
        let url = format!(
            "{}/entity-history/{}?sort-order={}&with-docs={}",
            self.uri,
            hash,
            order.serialize(),
            with_docs
        );
        let resp = self
            .client
            .get(&url)
            .headers(self.headers.clone())
            .send()
            .await?
            .text()
            .await?;

        EntityHistoryResponse::from_str(&resp.replace("#inst", ""))
    }

    pub async fn entity_history_timed(
        &self,
        hash: String,
        order: Order,
        with_docs: bool,
        time: Vec<crate::types::http::TimeHistory>,
    ) -> Result<EntityHistoryResponse, CruxError> {
        let url = format!(
            "{}/entity-history/{}?sort-order={}&with-docs={}{}",
            self.uri,
            hash,
            order.serialize(),
            with_docs,
            time.serialize().replace("[", "").replace("]", ""),
        );

        let resp = self
            .client
            .get(&url)
            .headers(self.headers.clone())
            .send()
            .await?
            .text()
            .await?;

        EntityHistoryResponse::from_str(&resp.replace("#inst", ""))
    }

    pub async fn query(&self, query: Query) -> Result<BTreeSet<Vec<String>>, CruxError> {
        let resp = self
            .client
            .post(&format!("{}/query", self.uri))
            .headers(self.headers.clone())
            .body(query.serialize())
            .send()
            .await?
            .text()
            .await?;

        let query_response: QueryAsyncResponse = edn_rs::from_str(&resp)?;

        Ok(query_response.0)
    }
}

fn build_timed_url(
    url: String,
    endpoint: &str,
    transaction_time: Option<DateTime<FixedOffset>>,
    valid_time: Option<DateTime<FixedOffset>>,
) -> String {
    match (transaction_time, valid_time) {
        (None, None) => format!("{}/{}", url, endpoint),
        (Some(tx), None) => format!(
            "{}/{}?transaction-time={}",
            url,
            endpoint,
            tx.format(DATE_FORMAT).to_string()
        ),
        (None, Some(valid)) => format!(
            "{}/{}?valid-time={}",
            url,
            endpoint,
            valid.format(DATE_FORMAT).to_string()
        ),
        (Some(tx), Some(valid)) => format!(
            "{}/{}?transaction-time={}&valid-time={}",
            url,
            endpoint,
            tx.format(DATE_FORMAT).to_string(),
            valid.format(DATE_FORMAT).to_string()
        ),
    }
    .replace("+", "%2B")
}

#[cfg(test)]
mod http {
    use crate::client::Crux;
    use crate::types::http::Action;
    use crate::types::http::Order;
    use crate::types::{
        query::Query,
        response::{EntityHistoryElement, EntityHistoryResponse, EntityTxResponse, TxLogResponse},
        CruxId,
    };
    use edn_rs::{ser_struct, Serialize};
    use mockito::mock;

    ser_struct! {
        #[derive(Debug, Clone)]
        #[allow(non_snake_case)]
        pub struct Person {
            crux__db___id: CruxId,
            first_name: String,
            last_name: String
        }
    }

    #[test]
    fn tx_log() {
        let _m = mock("POST", "/tx-log")
        .with_status(200)
        .match_body("[[:crux.tx/put { :crux.db/id :jorge-3, :first-name \"Michael\", :last-name \"Jorge\", }], [:crux.tx/put { :crux.db/id :manuel-1, :first-name \"Diego\", :last-name \"Manuel\", }]]")
        .with_header("content-type", "text/plain")
        .with_body("{:crux.tx/tx-id 8, :crux.tx/tx-time #inst \"2020-07-16T21:53:14.628-00:00\"}")
        .create();

        let person1 = Person {
            crux__db___id: CruxId::new("jorge-3"),
            first_name: "Michael".to_string(),
            last_name: "Jorge".to_string(),
        };

        let person2 = Person {
            crux__db___id: CruxId::new("manuel-1"),
            first_name: "Diego".to_string(),
            last_name: "Manuel".to_string(),
        };

        let action1 = Action::Put(person1.serialize(), None);
        let action2 = Action::Put(person2.serialize(), None);

        let response = Crux::new("localhost", "4000")
            .http_client()
            .tx_log(vec![action1, action2]);

        assert_eq!(response.unwrap(), TxLogResponse::default())
    }

    #[test]
    fn tx_logs() {
        let _m = mock("GET", "/tx-log")
        .with_status(200)
        .with_header("content-type", "application/edn")
        .with_body("({:crux.tx/tx-id 0, :crux.tx/tx-time #inst \"2020-07-09T23:38:06.465-00:00\", :crux.tx.event/tx-events [[:crux.tx/put \"a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e\" \"125d29eb3bed1bf51d64194601ad4ff93defe0e2\"]]}{:crux.tx/tx-id 1, :crux.tx/tx-time #inst \"2020-07-09T23:39:33.815-00:00\", :crux.tx.event/tx-events [[:crux.tx/put \"a15f8b81a160b4eebe5c84e9e3b65c87b9b2f18e\" \"1b42e0d5137e3833423f7bb958622bee29f91eee\"]]})")
        .create();

        let response = Crux::new("localhost", "4000").http_client().tx_logs();

        assert_eq!(response.unwrap().tx_events.len(), 2);
    }

    #[test]
    #[should_panic(expected = "ParseEdnError(\"\\\"H\\\" could not be parsed\")")]
    fn tx_log_error() {
        let _m = mock("GET", "/tx-log")
            .with_status(200)
            .with_header("content-type", "application/edn")
            .with_body("Holy errors!")
            .create();

        let _error = Crux::new("localhost", "4000")
            .http_client()
            .tx_logs()
            .unwrap();
    }

    #[test]
    fn entity() {
        let expected_body = "Map(Map({\":crux.db/id\": Key(\":hello-entity\"), \":first-name\": Str(\"Hello\"), \":last-name\": Str(\"World\")}))";
        let _m = mock("POST", "/entity")
            .with_status(200)
            .match_body("{:eid :ivan}")
            .with_header("content-type", "application/edn")
            .with_body("{:crux.db/id :hello-entity :first-name \"Hello\", :last-name \"World\"}")
            .create();

        let edn_body = Crux::new("localhost", "3000")
            .http_client()
            .entity(":ivan".to_string())
            .unwrap();

        let resp = format!("{:?}", edn_body);
        assert_eq!(resp, expected_body);
    }

    #[test]
    fn entity_tx() {
        let expected_body = "{:crux.db/id \"d72ccae848ce3a371bd313865cedc3d20b1478ca\", :crux.db/content-hash \"1828ebf4466f98ea3f5252a58734208cd0414376\", :crux.db/valid-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-time #inst \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28}";
        let _m = mock("POST", "/entity-tx")
            .with_status(200)
            .match_body("{:eid :ivan}")
            .with_header("content-type", "application/edn")
            .with_body(expected_body)
            .create();

        let body = Crux::new("localhost", "3000")
            .http_client()
            .entity_tx(":ivan".to_string())
            .unwrap();

        assert_eq!(body, EntityTxResponse::default());
    }

    #[test]
    fn simple_query() {
        let expected_body = "#{[:postgres \"Postgres\" true] [:mysql \"MySQL\" true]}";
        let _m = mock("POST", "/query")
            .with_status(200)
            .with_header("content-type", "application/edn")
            .with_body(expected_body)
            .create();

        let query = Query::find(vec!["?p1", "?n", "?s"])
            .unwrap()
            .where_clause(vec!["?p1 :name ?n", "?p1 :is-sql ?s", "?p1 :is-sql true"])
            .unwrap()
            .build();
        let body = Crux::new("localhost", "3000")
            .http_client()
            .query(query.unwrap())
            .unwrap();

        let response = format!("{:?}", body);
        assert_eq!(
            response,
            "{[\":mysql\", \"MySQL\", \"true\"], [\":postgres\", \"Postgres\", \"true\"]}"
        );
    }

    #[test]
    fn entity_history() {
        let expected_body = "({:crux.tx/tx-time \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28, :crux.db/valid-time \"2020-07-19T04:12:13.788-00:00\", :crux.db/content-hash  \"1828ebf4466f98ea3f5252a58734208cd0414376\"})";
        let _m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=false")
            .with_status(200)
            .with_header("content-type", "application/edn")
            .with_body(expected_body)
            .create();

        let edn_body = Crux::new("localhost", "3000")
            .http_client()
            .entity_history(
                "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(),
                Order::Asc,
                false,
            )
            .unwrap();

        let expected = EntityHistoryResponse {
            history: vec![EntityHistoryElement::default()],
        };

        assert_eq!(edn_body, expected);
    }

    #[test]
    fn entity_history_docs() {
        let expected_body = "({:crux.tx/tx-time \"2020-07-19T04:12:13.788-00:00\", :crux.tx/tx-id 28, :crux.db/valid-time \"2020-07-19T04:12:13.788-00:00\", :crux.db/content-hash  \"1828ebf4466f98ea3f5252a58734208cd0414376\", :crux.db/doc :docs})";
        let _m = mock("GET", "/entity-history/ecc6475b7ef9acf689f98e479d539e869432cb5e?sort-order=asc&with-docs=true")
            .with_status(200)
            .with_header("content-type", "application/edn")
            .with_body(expected_body)
            .create();

        let edn_body = Crux::new("localhost", "3000")
            .http_client()
            .entity_history(
                "ecc6475b7ef9acf689f98e479d539e869432cb5e".to_string(),
                Order::Asc,
                true,
            )
            .unwrap();

        let expected = EntityHistoryResponse {
            history: vec![EntityHistoryElement::default_docs()],
        };

        assert_eq!(edn_body, expected);
    }
}

#[cfg(test)]
mod build_url {
    use super::build_timed_url;
    use chrono::prelude::*;

    #[test]
    fn both_times_are_none() {
        let url = build_timed_url("localhost:3000".to_string(), "entity", None, None);

        assert_eq!(url, "localhost:3000/entity");
    }

    #[test]
    fn both_times_are_some() {
        let url = build_timed_url(
            "localhost:3000".to_string(),
            "entity",
            Some(
                "2020-08-09T18:05:29.301-03:00"
                    .parse::<DateTime<FixedOffset>>()
                    .unwrap(),
            ),
            Some(
                "2020-11-09T18:05:29.301-03:00"
                    .parse::<DateTime<FixedOffset>>()
                    .unwrap(),
            ),
        );

        assert_eq!(url, "localhost:3000/entity?transaction-time=2020-08-09T18:05:29-03:00&valid-time=2020-11-09T18:05:29-03:00");
    }

    #[test]
    fn only_tx_time_is_some() {
        let url = build_timed_url(
            "localhost:3000".to_string(),
            "entity",
            Some(
                "2020-08-09T18:05:29.301-03:00"
                    .parse::<DateTime<FixedOffset>>()
                    .unwrap(),
            ),
            None,
        );

        assert_eq!(
            url,
            "localhost:3000/entity?transaction-time=2020-08-09T18:05:29-03:00"
        );
    }

    #[test]
    fn only_valid_time_is_some() {
        let url = build_timed_url(
            "localhost:3000".to_string(),
            "entity",
            None,
            Some(
                "2020-08-09T18:05:29.301+03:00"
                    .parse::<DateTime<FixedOffset>>()
                    .unwrap(),
            ),
        );

        assert_eq!(
            url,
            "localhost:3000/entity?valid-time=2020-08-09T18:05:29%2B03:00"
        );
    }
}