Skip to content

Commit

Permalink
Refactoring and name changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinnstah committed Apr 13, 2024
1 parent f31cf0c commit 80e047d
Show file tree
Hide file tree
Showing 17 changed files with 159 additions and 106 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,6 @@ extension URLSession: NetworkAntenna {
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print(data)
print(response)
return FfiNetworkingResponse(statusCode: 400, body: data)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::fmt::Debug;
use std::collections::HashMap;
use crypto_service::client_trait::Client;
use reqwest::header::{HeaderMap};

#[derive(PartialEq, Debug, Clone)]
pub struct AlphaAdvantageClient {
Expand All @@ -24,8 +24,8 @@ impl Client for AlphaAdvantageClient {
self.base_url.clone()
}

fn get_headers(&self) -> HeaderMap {
HeaderMap::new()
fn get_headers(&self) -> HashMap<String, String> {
HashMap::new()
}
}

Expand Down
4 changes: 3 additions & 1 deletion crates/crypto-service-server/src/api_client/get.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@

use super::api_client::ApiClient;
use axum::http::StatusCode;
use crypto_service::client_trait::{Client, QueryItems};
use reqwest::{Request, Response};
use serde::{de::DeserializeOwned, Serialize};
use crate::api_client::post::Headers;

impl ApiClient {
pub async fn get<T, U, C: Client>(
Expand Down Expand Up @@ -60,7 +62,7 @@ impl ApiClient {

self.http_client
.get(url)
.headers(client_source.get_headers())
.headers(Headers::from(client_source.get_headers()).0)
.query(&query)
.build()
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(e.to_string())))
Expand Down
54 changes: 45 additions & 9 deletions crates/crypto-service-server/src/api_client/post.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
use super::api_client::ApiClient;
use std::{collections::HashMap, str::FromStr};

use super::api_client::{ApiClient};
use axum::http::StatusCode;
use crypto_service::client_trait::Client;
use reqwest::Request;
use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Request,
};
use serde::{de::DeserializeOwned, Serialize};

impl ApiClient {
Expand All @@ -10,12 +15,20 @@ impl ApiClient {
client_source: C,
path: &str,
body: R,
) -> Result<(StatusCode, axum::Json<U>), (StatusCode, axum::Json<String>)>
) -> Result<
(StatusCode, axum::Json<U>),
(StatusCode, axum::Json<String>),
>
where
U: DeserializeOwned,
{
let request = self.counstruct_post_request(client_source, path, body)?;
let response_bytes = self.execute_request(request).await?;
let request = self.counstruct_post_request(
client_source,
path,
body,
)?;
let response_bytes =
self.execute_request(request).await?;
println!("{:#?}", response_bytes);
self.deserialize_response::<U>(response_bytes).await
}
Expand All @@ -25,15 +38,38 @@ impl ApiClient {
client_source: C,
path: &str,
body: R,
) -> Result<Request, (StatusCode, axum::Json<String>)> {
) -> Result<Request, (StatusCode, axum::Json<String>)>
{
let mut url = client_source.get_base_url();
url.push_str(path);

self.http_client
.post(url)
.json(&body)
.headers(client_source.get_headers())
.headers(Headers::from(client_source.get_headers()).0)
.build()
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, axum::Json(e.to_string())))
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(e.to_string()),
)
})
}
}

pub struct Headers(pub HeaderMap);

impl From<HashMap<String, String>> for Headers {
fn from(value: HashMap<String, String>) -> Self {
let mut map: HeaderMap<HeaderValue> =
HeaderMap::new();
value.iter().map(|(k, v)| {
map.append(
HeaderName::from_str(k.as_str())
.expect("msg"),
v.parse().expect("Unwrapping value failed"),
)
});
Headers(map)
}
}
}
52 changes: 0 additions & 52 deletions crates/crypto-service-server/src/coin_watch/coin_watch_client.rs

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use super::coin_watch_client::CoinWatchClient;
use crate::state::AppState;
use axum::{extract::State, http::StatusCode, Json};
use crypto_service::coin_watch_service::models::{
use crypto_service::coin_watch_service::{coin_watch_client::CoinWatchClient, models::{
AggregatedCoinInformation, Coin, CoinHistoryRequest,
CoinMeta, CoinMetaRequest, ListOfCoinsRequest,
};
}};

pub async fn get_list_of_coins(
State(state): State<AppState>,
Expand Down
1 change: 0 additions & 1 deletion crates/crypto-service-server/src/coin_watch/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod coin_watch_client;
pub mod coin_watch_handlers;
2 changes: 1 addition & 1 deletion crates/crypto-service-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use axum::{
routing::{get, post},
Router,
};
use crypto_service::coin_watch_service::coin_watch_client::CoinWatchClient;
use crypto_service_server::{
alphavantage_api::{
alpha_client::AlphaAdvantageClient, alpha_handler,
},
api_client::api_client::ApiClient,
coin_watch::{
coin_watch_client::CoinWatchClient,
coin_watch_handlers,
},
state::AppState,
Expand Down
3 changes: 2 additions & 1 deletion crates/crypto-service-server/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crypto_service::coin_watch_service::coin_watch_client::CoinWatchClient;

use crate::{
alphavantage_api::alpha_client::AlphaAdvantageClient,
api_client::api_client::ApiClient,
coin_watch::coin_watch_client::CoinWatchClient,
};

#[derive(Debug, Clone)]
Expand Down
21 changes: 7 additions & 14 deletions crates/crypto-service-uniffi/src/api_client/gateway.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
use crate::{
api_client::network_antenna::{
ExternalClient, FFINetworkingRequest,
FFINetworkingResponse,
},
coin_watch_service::models::{
client_trait::Client, coin_watch_service::{coin_watch_client::CoinWatchClient, models::{
CoinHistory, CoinHistoryRequest, CoinMeta,
CoinMetaRequest, ListOfCoinsRequest,
},
}}, network_antenna::network_antenna::{FFINetworkingRequest, FFINetworkingResponse, NetworkAntenna}
};
use serde::{Deserialize, Serialize};
use serde_json::to_vec;
Expand All @@ -15,9 +11,6 @@ use std::sync::Arc;
use uniffi::{export, Object, Record};

use super::error::{FFIBridgeError, RustSideError};
use crate::api_client::network_antenna::{
CoinWatchExternalClient, NetworkAntenna,
};

#[derive(Object)]
pub struct Gateway {
Expand Down Expand Up @@ -47,7 +40,7 @@ impl Gateway {
&self,
limit: u32,
) -> Result<Vec<CoinMeta>, FFIBridgeError> {
let external_client = CoinWatchExternalClient::new(
let external_client = CoinWatchClient::new_with_key(
self.network_antenna.get_api_keys().coin_watch,
);
let request = ListOfCoinsRequest::new(limit);
Expand All @@ -65,7 +58,7 @@ impl Gateway {
&self,
request: CoinMetaRequest,
) -> Result<CoinMeta, FFIBridgeError> {
let external_client = CoinWatchExternalClient::new(
let external_client = CoinWatchClient::new_with_key(
self.network_antenna.get_api_keys().coin_watch,
);

Expand All @@ -82,7 +75,7 @@ impl Gateway {
&self,
request: CoinHistoryRequest,
) -> Result<CoinHistory, FFIBridgeError> {
let external_client = CoinWatchExternalClient::new(
let external_client = CoinWatchClient::new_with_key(
self.network_antenna.get_api_keys().coin_watch,
);

Expand Down Expand Up @@ -135,7 +128,7 @@ impl Gateway {
U: for<'a> Deserialize<'a> + std::fmt::Debug,
F: Fn(U) -> Result<V, E>,
E: Into<FFIBridgeError>,
C: ExternalClient,
C: Client,
{
// JSON serialize request into body bytes
let body = to_vec(&request).unwrap();
Expand Down Expand Up @@ -184,7 +177,7 @@ impl Gateway {
U: for<'a> Deserialize<'a> + std::fmt::Debug,
F: Fn(U) -> Result<V, E>,
E: Into<FFIBridgeError>,
C: ExternalClient,
C: Client,
{
self.make_request::<_, U, V, _, _, _>(
path, "POST", request, map, client,
Expand Down
1 change: 0 additions & 1 deletion crates/crypto-service-uniffi/src/api_client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod gateway;
pub mod network_antenna;
pub mod error;
32 changes: 19 additions & 13 deletions crates/crypto-service-uniffi/src/client_trait.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,24 @@
use core::fmt::Debug;
use std::collections::HashMap;
use reqwest::header::HeaderMap;

pub trait Asset: Send {

}
pub trait Asset: Send {}

pub trait Client: Debug {
fn get_base_url(&self) -> String;
fn get_headers(&self) -> HeaderMap;
fn get_headers(&self) -> HashMap<String, String>;
}

pub trait QueryItems {
type Query;
fn get_all_queries(&self) -> HashMap<&str, Self::Query>;
fn get_all_queries(&self)
-> HashMap<&str, Self::Query>;
}

#[cfg(test)]
#[derive(Debug)]
struct TestClient {
base_url: String,
headers: HeaderMap,
headers: HashMap<String, String>,
}

#[cfg(test)]
Expand All @@ -29,7 +27,7 @@ impl Client for TestClient {
self.base_url.clone()
}

fn get_headers(&self) -> HeaderMap {
fn get_headers(&self) -> HashMap<String, String> {
self.headers.clone()
}
}
Expand All @@ -43,7 +41,7 @@ mod tests {
fn get_base_url() {
let test_client = TestClient {
base_url: "http://www.apa.se".to_string(),
headers: HeaderMap::new(),
headers: HashMap::new(),
};
assert_eq!(
test_client.get_base_url(),
Expand All @@ -53,16 +51,24 @@ mod tests {

#[test]
fn get_headers() {
let mut headers = HeaderMap::new();
headers.insert("apa", "banan".parse().unwrap());
let mut headers = HashMap::new();
headers.insert(
"apa".to_string(),
"banan".parse().unwrap(),
);

let test_client = TestClient {
base_url: String::new(),
headers,
};

assert!(test_client.get_headers().contains_key("apa"));
assert_eq!(test_client.get_headers().get("apa").unwrap(), "banan")
assert!(test_client
.get_headers()
.contains_key("apa"));
assert_eq!(
test_client.get_headers().get("apa").unwrap(),
"banan"
)
}

// #[test]
Expand Down
Loading

0 comments on commit 80e047d

Please sign in to comment.