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
use hyper::{self, StatusCode}; use hyper::header::ContentType; use serde_json::to_string; use serde::ser::Serialize; use core::{res, JsonError, QueryParseError, Request, Response}; fn toStatusCode(number: u16) -> StatusCode { match StatusCode::try_from(number) { Ok(status) => status, Err(_) => StatusCode::BadRequest, } } impl<T: Serialize> From<(u16, T)> for Response { fn from(tuple: (u16, T)) -> Response { res() .with_header(ContentType::plaintext()) .with_status(toStatusCode(tuple.0)) .with_body(to_string(&tuple.1).unwrap()) } } impl<T: Serialize> From<T> for Response { default fn from(json: T) -> Response { res() .with_header(ContentType::json()) .with_status(toStatusCode(200)) .with_body(to_string(&json).unwrap()) } } impl From<Response> for hyper::Response { fn from(res: Response) -> hyper::Response { res.inner } } impl From<hyper::Request> for Request { fn from(req: hyper::Request) -> Request { let (method, uri, version, headers, body) = req.deconstruct(); let request = Request::new(method, uri, version, headers, body); request } } impl From<JsonError> for Response { fn from(error: JsonError) -> Response { match error { JsonError::None => { let json = json!({ "error": "Json was empty", }); res() .with_header(ContentType::json()) .with_body(to_string(&json).unwrap()) } JsonError::Err(e) => { let json = json!({ "error": format!("{}", e), }); res() .with_header(ContentType::json()) .with_body(to_string(&json).unwrap()) } } } } impl From<QueryParseError> for Response { fn from(error: QueryParseError) -> Response { match error { QueryParseError::None => { let json = json!({ "error": "query data was empty", }); res() .with_header(ContentType::json()) .with_body(to_string(&json).unwrap()) } QueryParseError::ParseError(_e) => { let json = json!({ "error": format!("{}", _e.message), }); res() .with_header(ContentType::json()) .with_body(to_string(&json).unwrap()) } QueryParseError::SerdeError(_e) => { let json = json!({ "error": format!("{}", _e), }); res() .with_header(ContentType::json()) .with_body(to_string(&json).unwrap()) } } } }