Skip to content

Commit

Permalink
bex: Extract request mod
Browse files Browse the repository at this point in the history
  • Loading branch information
bouzuya committed May 24, 2022
1 parent d103568 commit 90c8a34
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 47 deletions.
49 changes: 2 additions & 47 deletions bex/crates/pocket/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,56 +1,11 @@
mod access_token;
mod authorization;
mod error;
mod request;
mod retrieve;

pub use access_token::*;
pub use authorization::*;
pub use error::*;
use hyper::StatusCode;
use reqwest::Response;
pub(crate) use request::*;
pub use retrieve::*;
use serde::{de::DeserializeOwned, Serialize};

fn check_status_code(response: &Response) -> Option<Error> {
let status = response.status();
if status == StatusCode::OK {
return None;
}

let headers = response.headers();
let x_error_code = headers.get("X-Error-Code");
let x_error = headers.get("X-Error");
Some(Error::Status {
status_code: status.as_u16(),
x_error_code: x_error_code
.map(|v| v.to_str())
.transpose()
.unwrap()
.map(|v| v.to_owned()),
x_error: x_error
.map(|v| v.to_str())
.transpose()
.unwrap()
.map(|v| v.to_owned()),
})
}

async fn post<T, U>(url: &str, body: &T) -> Result<U, Error>
where
T: Serialize + ?Sized,
U: DeserializeOwned,
{
let client = reqwest::Client::new();
let response = client
.post(url)
.header("Content-Type", "application/json; charset=UTF8")
.header("X-Accept", "application/json")
.json(&body)
.send()
.await?;
if let Some(error) = check_status_code(&response) {
return Err(error);
}
let response_body = response.json::<U>().await?;
Ok(response_body)
}
49 changes: 49 additions & 0 deletions bex/crates/pocket/src/request.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use hyper::StatusCode;
use reqwest::Response;
use serde::{de::DeserializeOwned, Serialize};

use crate::Error;

fn check_status_code(response: &Response) -> Option<Error> {
let status = response.status();
if status == StatusCode::OK {
return None;
}

let headers = response.headers();
let x_error_code = headers.get("X-Error-Code");
let x_error = headers.get("X-Error");
Some(Error::Status {
status_code: status.as_u16(),
x_error_code: x_error_code
.map(|v| v.to_str())
.transpose()
.unwrap()
.map(|v| v.to_owned()),
x_error: x_error
.map(|v| v.to_str())
.transpose()
.unwrap()
.map(|v| v.to_owned()),
})
}

pub async fn post<T, U>(url: &str, body: &T) -> Result<U, Error>
where
T: Serialize + ?Sized,
U: DeserializeOwned,
{
let client = reqwest::Client::new();
let response = client
.post(url)
.header("Content-Type", "application/json; charset=UTF8")
.header("X-Accept", "application/json")
.json(&body)
.send()
.await?;
if let Some(error) = check_status_code(&response) {
return Err(error);
}
let response_body = response.json::<U>().await?;
Ok(response_body)
}

0 comments on commit 90c8a34

Please sign in to comment.