-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
lib.rs
87 lines (77 loc) · 2.34 KB
/
lib.rs
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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
mod errors;
use std::fmt;
pub use errors::PersistError;
use hyper::Body;
use hyper::Client;
use hyper::Method;
use hyper::Request;
use hyper_tls::HttpsConnector;
use serde::Deserialize;
use url::form_urlencoded;
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum Response {
Success { id: String },
Error { error: ResponseError },
}
#[derive(Debug, Deserialize)]
struct ResponseError {
message: String,
}
impl fmt::Display for ResponseError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
pub async fn persist(
document: &str,
uri: &str,
params: impl IntoIterator<Item = (&String, &String)>,
extra_headers: impl IntoIterator<Item = (&String, &String)>,
) -> Result<String, PersistError> {
let request_body = {
let mut request_body = form_urlencoded::Serializer::new(String::new());
for param in params {
request_body.append_pair(param.0, param.1);
}
request_body.append_pair("text", document);
request_body.finish()
};
let mut builder = Request::builder()
.method(Method::POST)
.uri(uri)
.header("content-type", "application/x-www-form-urlencoded");
for (k, v) in extra_headers {
builder = builder.header(k, v);
}
let req =
builder
.body(Body::from(request_body))
.map_err(|err| PersistError::NetworkCreateError {
error: Box::new(err),
})?;
let https = HttpsConnector::new();
let client = Client::builder().build(https);
let res = client.request(req).await?;
let bytes = hyper::body::to_bytes(res.into_body()).await?;
let result: Response =
serde_json::from_slice(&bytes).map_err(|err| PersistError::DetailedResponseParseError {
source: err,
raw_response: String::from_utf8_lossy(&bytes).to_string(),
})?;
match result {
Response::Success { id } => Ok(id),
Response::Error { error } => Err(PersistError::ErrorResponse {
message: error.message,
}),
}
}