Skip to content

Commit

Permalink
refactor: Firebase.at
Browse files Browse the repository at this point in the history
  • Loading branch information
jetjinser committed Mar 1, 2023
1 parent 2fbeda7 commit 09ae05d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 38 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@ keywords = ["firebase", "rest", "api", "web", "database"]

[dependencies]
url = "2.2.2"
reqwest = { version = "0.11.11", features = ["json"] }
reqwest = { version = "0.11.11", optional = true, features = ["json"] }
serde_json = "1.0.82"
serde = { version = "1.0.139", features = ["derive"] }
itertools = "0.10.5"

[dev-dependencies]
tokio = { version = "1.20.0", features = ["rt", "macros"] }

[features]
default = ["reqwest"]
68 changes: 32 additions & 36 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use constants::{Method, Response, AUTH};
use errors::{RequestError, RequestResult, UrlParseError, UrlParseResult};
use params::Params;
use reqwest::StatusCode;
use reqwest::{Client, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
Expand All @@ -26,28 +26,32 @@ impl Firebase {
/// let firebase = Firebase::new("https://myfirebase.firebaseio.com").unwrap();
/// ```
pub fn new(uri: &str) -> UrlParseResult<Self>
where
Self: Sized,
where
Self: Sized,
{
match check_uri(&uri) {
Ok(uri) => Ok(Self { uri }),
Ok(uri) => Ok(Self {
uri,
}),
Err(err) => Err(err),
}
}

/// ```
/// use firebase_rs::Firebase;
///
/// let firebase = Firebase::new("https://myfirebase.firebaseio.com").unwrap();
/// let firebase = Firebase::auth("https://myfirebase.firebaseio.com", "my_auth_key").unwrap();
/// ```
pub fn auth(uri: &str, auth_key: &str) -> UrlParseResult<Self>
where
Self: Sized,
where
Self: Sized,
{
match check_uri(&uri) {
Ok(mut uri) => {
uri.set_query(Some(&format!("{}={}", AUTH, auth_key)));
Ok(Self { uri })
Ok(Self {
uri,
})
}
Err(err) => Err(err),
}
Expand All @@ -71,28 +75,20 @@ impl Firebase {
///
/// let firebase = Firebase::new("https://myfirebase.firebaseio.com").unwrap().at("users").at("USER_ID").at("f69111a8a5258c15286d3d0bd4688c55");
/// ```
pub fn at(&self, path: &str) -> Self {
let mut new_path = String::default();

let paths = self.uri.path_segments().map(|p| p.collect::<Vec<_>>());
for mut path in paths.unwrap() {
if path.find(".json").is_some() {
path = path.trim_end_matches(".json");
}
new_path += format!("{}/", path).as_str();
}
pub fn at(&mut self, path: &str) -> &mut Self {
let re_path: String = self
.uri
.path_segments()
.unwrap_or_else(|| panic!("cannot be base"))
.map(|seg| format!("{}/", seg.trim_end_matches(".json")))
.collect();

new_path += path;
let new_path = re_path + path;

if new_path.find(".json").is_some() {
new_path = new_path.trim_end_matches(".json").to_string();
}
self.uri
.set_path(&format!("{}.json", new_path.trim_end_matches(".json")));

let mut uri = self.uri.clone();
uri.set_path(&format!("{}.json", new_path));
Self {
uri,
}
self
}

/// ```
Expand All @@ -106,7 +102,7 @@ impl Firebase {
}

async fn request(&self, method: Method, data: Option<Value>) -> RequestResult<Response> {
let client = reqwest::Client::new();
let client = Client::new();

return match method {
Method::GET => {
Expand Down Expand Up @@ -171,8 +167,8 @@ impl Firebase {
}

async fn request_generic<T>(&self, method: Method) -> RequestResult<T>
where
T: Serialize + DeserializeOwned + Debug,
where
T: Serialize + DeserializeOwned + Debug,
{
let request = self.request(method, None).await;

Expand Down Expand Up @@ -202,8 +198,8 @@ impl Firebase {
/// # }
/// ```
pub async fn set<T>(&self, data: &T) -> RequestResult<Response>
where
T: Serialize + DeserializeOwned + Debug,
where
T: Serialize + DeserializeOwned + Debug,
{
let data = serde_json::to_value(&data).unwrap();
self.request(Method::POST, Some(data)).await
Expand Down Expand Up @@ -249,8 +245,8 @@ impl Firebase {
/// # }
/// ```
pub async fn get<T>(&self) -> RequestResult<T>
where
T: Serialize + DeserializeOwned + Debug,
where
T: Serialize + DeserializeOwned + Debug,
{
self.request_generic::<T>(Method::GET).await
}
Expand Down Expand Up @@ -283,8 +279,8 @@ impl Firebase {
/// # }
/// ```
pub async fn update<T>(&self, data: &T) -> RequestResult<Response>
where
T: DeserializeOwned + Serialize + Debug,
where
T: DeserializeOwned + Serialize + Debug,
{
let value = serde_json::to_value(&data).unwrap();
self.request(Method::PATCH, Some(value)).await
Expand Down
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::UrlParseError;
use url::Url;

pub fn check_uri(uri: &str) -> UrlParseResult<Url> {
let uri = Url::parse(uri);
let uri = Url::parse(uri.trim_end_matches("/"));

let uri = match uri {
Ok(res) => res,
Expand Down

0 comments on commit 09ae05d

Please sign in to comment.