Added base communicator
This commit is contained in:
commit
dfd7b84b2c
|
@ -0,0 +1 @@
|
|||
/target
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,15 @@
|
|||
[package]
|
||||
name = "chat-communicators"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
[dependencies]
|
||||
tokio = { version = "1.20.1", features = ["full"] }
|
||||
reqwest = { version = "0.11.11", features = [ "json", "blocking" ]}
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
|
||||
chat-types = { git = "https://git.franklinblanco.dev/franklinblanco/chat-types.git" }
|
||||
|
||||
err = { git = "https://github.com/franklinblanco/err.git" }
|
||||
actix-web-utils = { git = "https://github.com/franklinblanco/actix-web-utils.git" }
|
|
@ -0,0 +1,4 @@
|
|||
use err::{Error, MessageResource};
|
||||
use serde::{Serialize};
|
||||
|
||||
pub async fn a() {}
|
|
@ -0,0 +1,56 @@
|
|||
pub mod chat;
|
||||
|
||||
use err::{Error, MessageResource};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
|
||||
pub async fn perform_request<B: Serialize, R: DeserializeOwned>(
|
||||
base_url: String,
|
||||
client: &reqwest::Client,
|
||||
method: reqwest::Method,
|
||||
path: String,
|
||||
body: Option<B>,
|
||||
expected_status_code: u16,
|
||||
headers: Vec<(String, String)>,
|
||||
) -> Result<R, Error> {
|
||||
let mut req_incomplete =
|
||||
client.request(method, format!("{url}{path}", url = base_url, path = path));
|
||||
|
||||
for header in headers {
|
||||
req_incomplete = req_incomplete.header(&header.0, &header.1);
|
||||
}
|
||||
|
||||
let req_complete = match body {
|
||||
Some(b) => req_incomplete.json(&b),
|
||||
None => req_incomplete.header("content-length", 0),
|
||||
};
|
||||
println!("{:?}", req_complete);
|
||||
match req_complete.send().await {
|
||||
// Error handling here
|
||||
Ok(res) => {
|
||||
// Request sent correctly
|
||||
match res.status().as_u16() == expected_status_code {
|
||||
true => {
|
||||
match res.json::<R>().await {
|
||||
Ok(resp_dto) => Ok(resp_dto), // Return correctly deserialized obj
|
||||
Err(err) => Err(Error::Serde(MessageResource::from(err))),
|
||||
}
|
||||
}
|
||||
false => {
|
||||
//If status code is any other than expected
|
||||
Err(Error::UnexpectedStatusCode(
|
||||
expected_status_code,
|
||||
res.status().as_u16(),
|
||||
match res.json::<Vec<MessageResource>>().await {
|
||||
Ok(messages) => messages,
|
||||
Err(e) => vec![MessageResource::from(e)],
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Request couldn't be sent
|
||||
Err(Error::Network(MessageResource::from(e)))
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
pub mod client;
|
Loading…
Reference in New Issue