From a058023e0563df17e493dcd502160dca1d6f384e Mon Sep 17 00:00:00 2001 From: Franklin Date: Thu, 8 Sep 2022 12:59:02 -0400 Subject: [PATCH] Added perform request without client --- src/middleware/client.rs | 54 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/middleware/client.rs b/src/middleware/client.rs index 5b1ef33..ad37a69 100644 --- a/src/middleware/client.rs +++ b/src/middleware/client.rs @@ -1,4 +1,5 @@ use actix_web_utils::{enums::error::Error, dtos::message::MessageResource}; +use reqwest::Client; use serde::{Serialize, de::DeserializeOwned}; pub async fn perform_request( @@ -17,6 +18,59 @@ pub async fn perform_request( 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::().await { + Ok(resp_dto) => Ok(resp_dto), // Return correctly deserialized obj + Err(err) => Err(Error::ClientError(MessageResource::new_from_err(err))), + } + } + false => { + //If status code is any other than expected + Err(Error::UnexpectedStatusCode( + expected_status_code, + res.status().as_u16(), + match res.json::>().await { + Ok(messages) => messages, + Err(e) => vec![MessageResource::new_from_err(e.to_string())], + }, + )) + } + } + } + Err(e) => { + // Request couldn't be sent + Err(Error::ClientError(MessageResource::new_from_err(e))) + } + } +} +/// This function is mainly for when you don't have a client in your application and just want to get it over with. +/// This shouldn't be used as it takes more resource consumption than the above method. +pub async fn perform_request_without_client( + base_url: String, + method: reqwest::Method, + path: String, + body: Option, + expected_status_code: u16, + headers: Vec<(String, String)>, +) -> Result { + let client = Client::new(); + 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),