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
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use regex::{Regex, Captures};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::Method;

use crate::errors::FhttpError;
use crate::errors::Result;
use crate::path_utils::get_dependency_path;
use apply::Also;

pub mod response_handler;
pub mod variable_support;
pub mod body;
pub mod has_body;

lazy_static!{
    pub static ref RE_REQUEST: Regex = Regex::new(r#"(?m)\$\{request\("([^"]+)"\)}"#).unwrap();
}

#[derive(Debug, Eq)]
pub struct Request {
    pub source_path: PathBuf,
    pub text: String,
    pub dependency: bool,
}

impl Request {

    pub fn new<P: Into<PathBuf>, T: Into<String>>(
        path: P,
        text: T
    ) -> Result<Self> {
        Request::_new(path, text, false)
    }

    pub fn depdendency<P: Into<PathBuf>, T: Into<String>>(
        path: P,
        text: T
    ) -> Result<Self> {
        Request::_new(path, text, true)
    }

    pub fn from_file(
        path: &Path,
        dependency: bool,
    ) -> Result<Self> {
        let path = fs::canonicalize(&path)
            .map_err(|_| FhttpError::new(format!("cannot convert {} to an absolute path", path.to_str().unwrap())))?;
        let content = fs::read_to_string(&path)
            .map_err(|_| FhttpError::new(format!("error reading file {}", path.to_str().unwrap())))?;

        match dependency {
            true => Request::depdendency(&path, content),
            false => Request::new(&path, content),
        }
    }

    fn _new<P: Into<PathBuf>, T: Into<String>>(
        path: P,
        text: T,
        dependency: bool
    ) -> Result<Self> {
        let mut ret = Request {
            source_path: path.into(),
            text: text.into(),
            dependency,
        };

        ret._replace_includes()?;

        Ok(ret)
    }

    pub fn method(&self) -> Result<Method> {
        let first_line = self.first_line()?;
        let split: Vec<&str> = first_line.splitn(2, ' ').collect();
        let method_string = split[0];

        Method::from_str(method_string)
            .map_err(|_| FhttpError::new(format!("Couldn't parse method '{}'", method_string)))
    }

    pub fn url(&self) -> Result<&str> {
        let first_line = self.first_line()?;
        let mut split: Vec<&str> = first_line.splitn(2, ' ').collect();

        split.pop()
            .ok_or(FhttpError::new("Malformed url line"))
    }

    pub fn headers(&self) -> Result<HeaderMap> {
        let lines = self.text.lines()
            .map(|line| line.trim())
            .filter(|line| !line.starts_with('#'))
            .skip(1)
            .collect::<Vec<&str>>();

        let mut ret = HeaderMap::new();
        for line in lines {
            if line.is_empty() {
                break;
            }

            let split: Vec<&str> = line.splitn(2, ':').collect();
            let key = HeaderName::from_str(split[0].trim())
                .expect("couldn't create HeaderName");
            let value_text = split[1].trim();
            let value = HeaderValue::from_str(value_text).unwrap();
            ret.insert(key, value);
        }

        if self.gql_file() {
            ret.entry("content-type")
                .or_insert(HeaderValue::from_static("application/json"));
        }

        Ok(ret)
    }

    pub fn dependencies(&self) -> Vec<PathBuf> {
        let mut ret = vec![];
        for capture in RE_REQUEST.captures_iter(&self.text) {
            let group = capture.get(1).unwrap().as_str();
            let path = self.get_dependency_path(group);
            ret.push(path);
        }
        ret
    }

    fn first_line(&self) -> Result<&str> {
        self.text.lines()
            .map(|line| line.trim())
            .filter(|line| !line.starts_with("#"))
            .nth(0)
            .ok_or(FhttpError::new("Could not find first line"))
    }

    pub fn gql_file(&self) -> bool {
        let filename = self.source_path.file_name().unwrap().to_str().unwrap();

        filename.ends_with(".gql.http") || filename.ends_with(".graphql.http")
    }

    pub fn get_dependency_path(
        &self,
        path: &str
    ) -> PathBuf {
        get_dependency_path(
            &self.source_path,
            path
        )
    }

    fn _replace_includes(&mut self) -> Result<()> {
        lazy_static! {
            static ref RE_ENV: Regex = Regex::new(r##"(?m)\$\{include\("([^"]*)"\)}"##).unwrap();
        };

        let reversed_captures: Vec<Captures> = RE_ENV.captures_iter(&self.text)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();

        if !reversed_captures.is_empty() {
            let mut buffer = self.text.clone();

            for capture in reversed_captures {
                let group = capture.get(0).unwrap();
                let range = group.start()..group.end();
                let path = capture.get(1).unwrap().as_str();
                let path = get_dependency_path(&self.source_path, path);
                let content = std::fs::read_to_string(&path)
                    .map_err(|_| FhttpError::new(format!("error reading file {}", path.to_str().unwrap())))?;
                let content = match content.chars().last() {
                    Some('\n') => content.also(|it| it.truncate(it.len() - 1)),
                    _ => content,
                };

                buffer.replace_range(range, &content);
            }

            self.text = buffer;
        }

        Ok(())
    }
}

impl PartialEq for Request {
    fn eq(
        &self,
        other: &Self
    ) -> bool {
        self.source_path == other.source_path
    }
}

#[cfg(test)]
mod test {
    use indoc::indoc;

    use crate::request::body::Body;
    use crate::request::has_body::HasBody;

    use super::*;

    #[test]
    fn method() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            # comment
            POST http://localhost:8080
        "##))?;

        assert_eq!(req.method()?, Method::POST);

        Ok(())
    }

    #[test]
    fn method_no_first_line() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            # comment
            # POST http://localhost:8080
        "##))?;

        assert_eq!(req.method(), Err(FhttpError::new("Could not find first line")));

        Ok(())
    }

    #[test]
    fn url() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            # comment
            POST http://localhost:8080
        "##))?;

        assert_eq!(req.url()?, "http://localhost:8080");

        Ok(())
    }

    #[test]
    fn headers() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            # comment
            POST http://localhost:8080
            # comment
            content-type: application/json; charset=UTF-8
            accept: application/json

            not-a-header: not-a-header-value
        "##))?;

        let mut expected_headers = HeaderMap::new();
        expected_headers.insert(HeaderName::from_str("content-type").unwrap(), HeaderValue::from_str("application/json; charset=UTF-8").unwrap());
        expected_headers.insert(HeaderName::from_str("accept").unwrap(), HeaderValue::from_str("application/json").unwrap());
        assert_eq!(req.headers()?, expected_headers);

        Ok(())
    }

    #[test]
    fn body() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            POST http://localhost:8080

            this is the body

            this as well

            > {%
                json $
            %}
        "##))?;

        assert_eq!(
            req.body()?,
            Body::plain(indoc!(r##"
                this is the body

                this as well
            "##))
        );

        Ok(())
    }

    #[test]
    fn no_body_should_return_empty_string() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            POST http://localhost:8080
        "##))?;

        assert_eq!(req.body()?, Body::plain(""));

        Ok(())
    }

    #[test]
    fn no_body_with_response_handler_should_return_empty_string() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            POST http://localhost:8080

            > {%
                json $
            %}
        "##))?;

        assert_eq!(req.body()?, Body::plain(""));

        Ok(())
    }
}

#[cfg(test)]
mod fileupload {
    use indoc::indoc;

    use crate::request::body::{Body, File};
    use crate::request::has_body::HasBody;
    use crate::test_utils::root;

    use super::*;

    #[test]
    fn test() -> Result<()> {
        let req = Request::new(std::env::current_dir().unwrap(), indoc!(r##"
            POST http://localhost:8080

            ${file("partname", "../resources/it/profiles.json")}
            ${file(
                "file",
                "../resources/it/profiles2.json"
            )}
        "##))?;

        assert_eq!(
            req.body()?,
            Body::Files(vec![
                File {
                    name: String::from("partname"),
                    path: root().join("resources/it/profiles.json")
                },
                File {
                    name: String::from("file"),
                    path: root().join("resources/it/profiles2.json")
                }
            ])
        );

        Ok(())
    }

}

#[cfg(test)]
mod gql {
    use std::fs;

    use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
    use reqwest::Method;
    use serde_json::json;
    use serde_json::value::Value;

    use indoc::indoc;
    use response_handler::RequestResponseHandlerExt;

    use crate::request::body::Body;
    use crate::request::has_body::HasBody;
    use crate::test_utils::root;

    use super::*;

    #[test]
    fn parse_gql_with_query_variables_response_handler() -> Result<()> {
        let source_path = std::env::current_dir().unwrap().join("foo.gql.http");
        let input = indoc!(r##"
            POST http://server:8080/graphql
            Authorization: Bearer token

            query($var: String!) {
                entity(id: $var, foo: "bar") {
                    field1
                    field2
                }
            }

            {
                "var": "entity-id"
            }

            > {%
                json $
            %}
        "##).to_owned();

        let result = Request::new(&source_path, input)?;

        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_str("Authorization").unwrap(), HeaderValue::from_str("Bearer token").unwrap());
        headers.insert(HeaderName::from_str("content-type").unwrap(), HeaderValue::from_str("application/json").unwrap());

        let expected_body = json!({
            "query": "query($var: String!) {\n    entity(id: $var, foo: \"bar\") {\n        field1\n        field2\n    }\n}",
            "variables": {
                "var": "entity-id"
            }
        });
        let body = match result.body()? {
            Body::Plain(body) => serde_json::from_str::<Value>(&body).unwrap(),
            _ => panic!("aaaaah!")
        };

        assert_eq!(result.method()?, Method::POST);
        assert_eq!(result.url()?, "http://server:8080/graphql");
        assert_eq!(result.headers()?, headers);
        assert_eq!(body, expected_body);
        assert_eq!(result.source_path, source_path);
        assert_eq!(result.dependency, false);
        assert!(result.response_handler()?.is_some());

        Ok(())
    }

    #[test]
    fn parse_gql_with_query_variables() -> Result<()> {
        let source_path = std::env::current_dir().unwrap().join("foo.gql.http");
        let input = indoc!(r##"
            POST http://server:8080/graphql
            Authorization: Bearer token

            query($var: String!) {
                entity(id: $var, foo: "bar") {
                    field1
                    field2
                }
            }

            {
                "var": "entity-id"
            }
        "##).to_owned();

        let result = Request::new(&source_path, input)?;

        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_str("Authorization").unwrap(), HeaderValue::from_str("Bearer token").unwrap());
        headers.insert(HeaderName::from_str("content-type").unwrap(), HeaderValue::from_str("application/json").unwrap());

        let expected_body = json!({
            "query": "query($var: String!) {\n    entity(id: $var, foo: \"bar\") {\n        field1\n        field2\n    }\n}",
            "variables": {
                "var": "entity-id"
            }
        });
        let body = match result.body()? {
            Body::Plain(body) => serde_json::from_str::<Value>(&body).unwrap(),
            _ => panic!("aaaaah!"),
        };

        assert_eq!(result.method()?, Method::POST);
        assert_eq!(result.url()?, "http://server:8080/graphql");
        assert_eq!(result.headers()?, headers);
        assert_eq!(body, expected_body);
        assert_eq!(result.source_path, source_path);
        assert_eq!(result.dependency, false);
        assert!(result.response_handler()?.is_none());

        Ok(())
    }

    #[test]
    fn parse_gql_with_query_response_handler() -> Result<()> {
        let source_path = std::env::current_dir().unwrap().join("foo.gql.http");
        let input = indoc!(r##"
            POST http://server:8080/graphql
            Authorization: Bearer token

            query($var: String!) {
                entity(id: $var, foo: "bar") {
                    field1
                    field2
                }
            }

            > {%
                json $
            %}
        "##).to_owned();

        let result = Request::new(&source_path, input)?;

        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_str("Authorization").unwrap(), HeaderValue::from_str("Bearer token").unwrap());
        headers.insert(HeaderName::from_str("content-type").unwrap(), HeaderValue::from_str("application/json").unwrap());

        let expected_body = json!({
            "query": "query($var: String!) {\n    entity(id: $var, foo: \"bar\") {\n        field1\n        field2\n    }\n}\n",
            "variables": {}
        });
        let body = match result.body()? {
            Body::Plain(body) => serde_json::from_str::<Value>(&body).unwrap(),
            _ => panic!("aaaaah!"),
        };

        assert_eq!(result.method()?, Method::POST);
        assert_eq!(result.url()?, "http://server:8080/graphql");
        assert_eq!(result.headers()?, headers);
        assert_eq!(body, expected_body);
        assert_eq!(result.source_path, source_path);
        assert_eq!(result.dependency, false);
        assert!(result.response_handler()?.is_some());

        Ok(())
    }

    #[test]
    fn parse_gql_with_query() -> Result<()> {
        let source_path = std::env::current_dir().unwrap().join("foo.gql.http");
        let input = indoc!(r##"
            POST http://server:8080/graphql
            Authorization: Bearer token

            query($var: String!) {
                entity(id: $var, foo: "bar") {
                    field1
                    field2
                }
            }
        "##).to_owned();

        let result = Request::new(
            &source_path,
            input
        )?;

        let mut headers = HeaderMap::new();
        headers.insert(HeaderName::from_str("Authorization").unwrap(), HeaderValue::from_str("Bearer token").unwrap());
        headers.insert(HeaderName::from_str("content-type").unwrap(), HeaderValue::from_str("application/json").unwrap());

        let expected_body = json!({
            "query": "query($var: String!) {\n    entity(id: $var, foo: \"bar\") {\n        field1\n        field2\n    }\n}\n",
            "variables": {}
        });

        let body = match result.body()? {
            Body::Plain(body) => serde_json::from_str::<Value>(&body).unwrap(),
            _ => panic!("aaaaah!"),
        };

        assert_eq!(result.method()?, Method::POST);
        assert_eq!(result.url()?, "http://server:8080/graphql");
        assert_eq!(result.headers()?, headers);
        assert_eq!(body, expected_body);
        assert_eq!(result.source_path, source_path);
        assert_eq!(result.dependency, false);
        assert!(result.response_handler()?.is_none());

        Ok(())
    }

    #[test]
    fn parse_should_parse_gql_based_on_filename() -> Result<()> {
        let root = root()
            .join("resources/test/requests/gql");
        let http_extension = root.join("request.http");
        let gql_http_extension = root.join("request.gql.http");

        let http_extension_result = Request::new(
            &http_extension,
            fs::read_to_string(&http_extension).unwrap()
        )?;

        let gql_http_extension_result = Request::new(
            &gql_http_extension,
            fs::read_to_string(&gql_http_extension).unwrap(),
        )?;

        match http_extension_result.body()? {
            Body::Plain(body) => assert!(&body.starts_with("query")),
            _ => panic!("aaaah!"),
        };

        let json_body = match gql_http_extension_result.body()? {
            Body::Plain(body) => serde_json::from_str::<Value>(&body),
            _ => panic!("aaaaah!"),
        };

        assert!(json_body.is_ok());
        match json_body.unwrap() {
            Value::Object(map) => {
                assert!(map.contains_key("query"));
                assert!(map.contains_key("variables"));
            },
            _ => panic!("expected a Value::Object!")
        }

        Ok(())
    }

    #[test]
    fn parse_qgl_should_set_contenttype_if_not_given() -> Result<()> {
        let dummy_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("resources/test/requests/dummy.gql.http");
        let json = HeaderValue::from_str("application/json").unwrap();
        let xml = HeaderValue::from_str("application/xml").unwrap();

        let req = Request::new(
            &dummy_path,
            indoc!(r##"
            POST http://graphql

            query {
                foo
            }
            "##)
        )?;
        assert!(req.headers()?.contains_key(&HeaderName::from_str("content-type").unwrap()));
        assert_eq!(req.headers()?.get(&HeaderName::from_str("content-type").unwrap()), Some(&json));

        let req = Request::new(
            &dummy_path,
            indoc!(r##"
            POST http://graphql
            Content-type: application/xml

            query {
                foo
            }
            "##),
        )?;
        assert_eq!(req.headers()?.get(&HeaderName::from_str("content-type").unwrap()), Some(&xml));

        Ok(())
    }
}

#[cfg(test)]
mod dependencies {
    use crate::test_utils::root;

    use super::*;

    #[test]
    fn should_find_dependencies() -> Result<()> {
        let source_path = root();
        let input = format!(r##"GET http://${{request("resources/test/requests/nested_dependencies/1.http")}}:8080
Authorization: Bearer ${{request("./../fhttp/resources/test/requests/nested_dependencies/2.http")}}

${{request("{}")}}
"##,
            source_path.join("resources/test/requests/nested_dependencies/3.http").to_str().unwrap()
        );

        let req = Request::new(&source_path, input)?;
        let dependencies = req.dependencies();

        assert_eq!(
            dependencies,
            vec![
                source_path.join("resources/test/requests/nested_dependencies/1.http"),
                source_path.join("resources/test/requests/nested_dependencies/2.http"),
                source_path.join("resources/test/requests/nested_dependencies/3.http"),
            ]
        );

        Ok(())
    }
}

#[cfg(test)]
mod includes {
    use std::env;

    use indoc::indoc;

    use crate::Result;

    use super::*;

    #[test]
    fn should_include_files_on_instantiation() -> Result<()> {
        let req = Request::new(
            env::current_dir().unwrap(),
            indoc!(r##"
                GET http://server

                ${include("../resources/it/requests/include_1.txt")}
                ${include("../resources/it/requests/include_2.txt")}
            "##)
        )?;

        assert_eq!(
            &req.text,
            indoc!(r##"
                GET http://server

                111
                2222
            "##)
        );

        Ok(())
    }

}