Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: duplicated params #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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
33 changes: 20 additions & 13 deletions src/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ use crate::constants::{
END_AT, EQUAL_TO, EXPORT, FORMAT, LIMIT_TO_FIRST, LIMIT_TO_LAST, ORDER_BY, SHALLOW, START_AT,
};
use crate::Firebase;
use itertools::Itertools;
use std::collections::HashMap;
use url::Url;
use itertools::Itertools;

#[derive(Debug)]
pub struct Params {
Expand All @@ -27,11 +27,10 @@ impl Params {
}

pub fn add_param<T>(&mut self, key: &str, value: T) -> &mut Self
where
T: ToString,
where
T: ToString,
{
self.params.insert(key.to_string(), value.to_string());
self.set_params();

self
}
Expand Down Expand Up @@ -68,26 +67,34 @@ impl Params {
self.add_param(FORMAT, EXPORT)
}

pub fn finish(&self) -> Firebase {
pub fn finish(&mut self) -> Firebase {
self.set_params();
Firebase::new(self.uri.as_str()).unwrap()
}
}


#[cfg(test)]
mod tests {
use crate::params::Params;
use std::collections::HashMap;
use url::Url;
use crate::params::Params;

#[test]
fn check_params() {
let mut params: HashMap<String, String> = HashMap::new();
params.insert("param_1".to_owned(), "value_1".to_owned());
params.insert("param_2".to_owned(), "value_2".to_owned());
let mut param = Params { uri: Url::parse("https://github.com/emreyalvac").unwrap(), params };
let mut params = HashMap::new();
params.insert("param_1", "value_1");
params.insert("param_2", "value_2");

let mut param = Params::new(Url::parse("https://github.com/emreyalvac").unwrap());

for (k, v) in params {
param.add_param(&k, v);
}
param.set_params();

assert_eq!(param.uri.as_str(), "https://github.com/emreyalvac?param_1=value_1&param_2=value_2")
assert_eq!(
param.uri.as_str(),
"https://github.com/emreyalvac?param_1=value_1&param_2=value_2"
)
}
}
}
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