From 97401342b18a12029827a85e89a0b1b25fce932a Mon Sep 17 00:00:00 2001 From: Awayume Date: Sun, 17 Sep 2023 15:13:41 +0900 Subject: [PATCH] add: add a trait for parsing query --- src/lib.rs | 16 +++----------- url_parser_trait/src/lib.rs | 43 ++++++++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7d12d9a..40cd894 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,4 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right -} +// SPDX-FileCopyrightText: 2023 Awayume +// 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; diff --git a/url_parser_trait/src/lib.rs b/url_parser_trait/src/lib.rs index 7d12d9a..7f8ade7 100644 --- a/url_parser_trait/src/lib.rs +++ b/url_parser_trait/src/lib.rs @@ -1,14 +1,47 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right +// SPDX-FileCopyrightText: 2023 Awayume +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashMap; + + +pub trait QueryParams { + fn get_items_as_string_map(&self) -> HashMap; + + fn to_query_params(&self) -> String { + let items: HashMap = 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 { + let mut map: HashMap = 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!(¶m.to_query_params(), "?user_id=1&user_name=Awayume"); } }