rede_parser/
lib.rs

1//! Library to handle the parsing of requests in TOML format used by the crate `rede`.
2//!
3//! The library offers the function [`rede_parser::parse_request`](parse_request)
4//! to convert a given string into a valid rede [`rede_schema::Request`](Request).
5//!
6//! # Example
7//!
8//! Pass the correct request TOML to the parser functions to get the parsed request:
9//!
10//! ```
11//! # use http::Method;
12//! # use rede_schema::body::Body;
13//! # use std::error::Error;
14//!
15//! # fn main() -> Result<(), Box<dyn Error>> {
16//! let toml = r#"
17//!     [http]
18//!     method = "POST"
19//!     url = "http://localhost:8080/note"
20//!
21//!     [headers]
22//!     Content-Type = "application/json"
23//!
24//!     [body]
25//!     raw = """
26//!     {
27//!         "title": "Implement rede_parser" ,
28//!         "description": "Implement it following the example
29//!     }
30//!     """
31//!  "#;
32//!  let request = rede_parser::parse_request(toml)?;
33//!  assert_eq!(request.method, Method::POST);
34//!  assert_eq!(request.url, "http://localhost:8080/note");
35//!  assert_eq!(request.headers["Content-Type"], "application/json");
36//!  if let Body::Raw { content, mime } = &request.body {
37//!     assert_eq!(mime, &"text/plain; charset=utf-8");
38//!     println!("{}", &request.body);
39//!  }
40//!  # Ok(())
41//! # }
42//! ```
43
44#![warn(clippy::pedantic)]
45#![allow(clippy::module_name_repetitions)]
46
47mod error;
48mod request;
49mod schema;
50
51use crate::schema::Schema;
52use std::str::FromStr;
53
54#[doc(inline)]
55pub use error::Error;
56
57/// Attempts to parse the given string into an HTTP request.
58///
59/// # Example
60///
61/// Passing the contents of a valid request TOML will provide a [Request]
62///
63/// ```
64/// # use std::error::Error;
65/// # fn main() -> Result<(), Box<dyn Error>> {
66/// let toml = r#"
67///  http = { url = "http://localhost:8080", method = "GET" }
68/// "#;
69/// let request = rede_parser::parse_request(toml)?;
70/// assert_eq!(request.url, "http://localhost:8080");
71/// assert_eq!(request.method, "GET");
72/// #    Ok(())
73/// # }
74///```
75/// # Errors
76///
77/// Some possible errors are:
78/// - The contents are not a valid TOML file
79/// - A required key is missing
80/// - At least one is the wrong type
81///
82/// ```
83/// # use std::error::Error;
84/// # fn main() {
85/// let toml = r#"
86///  http = { url = "http://localhost:8080", method = "GET" }
87///  query_params = { since = 1970-01-01 }
88/// "#;
89/// let result = rede_parser::parse_request(toml);
90/// assert!(result.is_err());
91/// # }
92/// ```
93pub fn parse_request(content: &str) -> Result<rede_schema::Request, Error> {
94    let schema = Schema::from_str(content)?;
95    let request = rede_schema::Request::try_from(schema)?;
96    Ok(request)
97}