wasm_framework/
method.rs

1use std::fmt;
2use wasm_bindgen::JsValue;
3
4/// HTTP Method
5#[derive(Clone, Copy, PartialEq, Debug)]
6#[allow(clippy::upper_case_acronyms)]
7pub enum Method {
8    /// HTTP GET method
9    GET,
10    /// HTTP POST method
11    POST,
12    /// HTTP PUT method
13    PUT,
14    /// HTTP DELETE method
15    DELETE,
16    /// HTTP HEAD method
17    HEAD,
18    /// HTTP OPTIONS method
19    OPTIONS,
20}
21
22impl Method {
23    /// Converts string to Method
24    pub fn from(s: &str) -> Result<Method, JsValue> {
25        Ok(match s {
26            "GET" | "get" => Method::GET,
27            "POST" | "post" => Method::POST,
28            "PUT" | "put" => Method::PUT,
29            "DELETE" | "delete" => Method::DELETE,
30            "HEAD" | "head" => Method::HEAD,
31            "OPTIONS" | "options" => Method::OPTIONS,
32            _ => return Err(JsValue::from_str("Unsupported http method")),
33        })
34    }
35}
36
37impl fmt::Display for Method {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
39        write!(
40            f,
41            "{}",
42            match self {
43                Method::GET => "GET",
44                Method::POST => "POST",
45                Method::PUT => "PUT",
46                Method::DELETE => "DELETE",
47                Method::HEAD => "HEAD",
48                Method::OPTIONS => "OPTIONS",
49            }
50        )
51    }
52}
53
54#[test]
55fn method_str() {
56    // to_string() and from()
57    assert_eq!(Method::from("GET").unwrap().to_string(), "GET");
58    assert_eq!(Method::from("POST").unwrap().to_string(), "POST");
59    assert_eq!(Method::from("PUT").unwrap().to_string(), "PUT");
60    assert_eq!(Method::from("DELETE").unwrap().to_string(), "DELETE");
61    assert_eq!(Method::from("HEAD").unwrap().to_string(), "HEAD");
62    assert_eq!(Method::from("OPTIONS").unwrap().to_string(), "OPTIONS");
63
64    // PartialEq
65    assert!(Method::from("GET").unwrap() == Method::GET);
66
67    // Debug
68    assert_eq!(format!("{:?}", Method::PUT), "PUT");
69
70    // parse error
71    // moved this to tests/method.rs because it depends on web_sys::JsValue
72    //assert!(Method::from("none").is_err());
73}