Skip to content

Commit

Permalink
add: add a trait for parsing query
Browse files Browse the repository at this point in the history
  • Loading branch information
Awayume committed Sep 17, 2023
1 parent e67a1b4 commit 9740134
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 18 deletions.
16 changes: 3 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,4 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
}
// SPDX-FileCopyrightText: 2023 Awayume <[email protected]>
// SPDX-License-Identifier: Apache-2.0

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}
pub use url_parser_trait::QueryParams;
43 changes: 38 additions & 5 deletions url_parser_trait/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,47 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
// SPDX-FileCopyrightText: 2023 Awayume <[email protected]>
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;


pub trait QueryParams {
fn get_items_as_string_map(&self) -> HashMap<String, String>;

fn to_query_params(&self) -> String {
let items: HashMap<String, String> = self.get_items_as_string_map();
let mut query: String = "?".to_string();

for (key, value) in items {
query += &format!("{}={}&", key, value);
}

query.pop();
query
}
}


#[cfg(test)]
mod tests {
use super::*;

struct Param {
user_id: u8,
user_name: String,
}

impl QueryParams for Param {
fn get_items_as_string_map(&self) -> HashMap<String, String> {
let mut map: HashMap<String, String> = HashMap::new();
map.insert("user_id".to_string(), self.user_id.to_string());
map.insert("user_name".to_string(), self.user_name.clone());
map
}
}

#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
fn check_query() {
let param: Param = Param {user_id: 1, user_name: "Awayume".to_string()};
assert_eq!(&param.to_query_params(), "?user_id=1&user_name=Awayume");
}
}

0 comments on commit 9740134

Please sign in to comment.