Created
April 27, 2022 16:37
-
-
Save jayhuang75/b14a12efe17dab208c3655c4ec9c121e to your computer and use it in GitHub Desktop.
rust-velocity-limit-impl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| impl Transaction { | |
| pub fn is_duplicate(&self) -> bool { | |
| let unique_key : &str = &format!("{}{}", self.id, self.customer_id); | |
| let store = TRANSACTION_ID_COUNT.lock().unwrap(); | |
| match store.get_mut(unique_key) { | |
| Some(_) => { | |
| return true | |
| } | |
| None => { | |
| store.insert(unique_key.to_owned(), 1); | |
| } | |
| } | |
| return false; | |
| } | |
| pub fn by_max_amount_transactions_per_day(&self, max: f64) -> bool { | |
| if self.format_currency() > max { | |
| return false; | |
| } | |
| return true; | |
| } | |
| pub fn by_week_transactions(&self, weekly_max_amount: f64) -> bool { | |
| let unique_key: &str = &format!("{}_{}", self.customer_id, self.get_week_transaction_ref()); | |
| let amount = self.format_currency(); | |
| let store = WEEKLY_TRANSACTIONS.lock().unwrap(); | |
| match store.get_mut(unique_key) { | |
| Some(mut count) => { | |
| *count += amount; | |
| }, | |
| None => { | |
| store.insert(unique_key.to_owned(), amount); | |
| } | |
| } | |
| if *store.get(unique_key).unwrap() > weekly_max_amount { | |
| return false; | |
| } | |
| return true; | |
| } | |
| pub fn by_day_transactions(&self, max_count: i32) -> bool { | |
| let unique_key : &str = &format!("{}_{}", self.customer_id, &self.time[..10]); | |
| let store = DAILY_TRANSACTIONS.lock().unwrap(); | |
| match store.get_mut(unique_key) { | |
| Some(mut count) => { | |
| *count += 1; | |
| }, | |
| None => { | |
| store.insert(unique_key.to_owned(), 1); | |
| } | |
| } | |
| if *store.get(unique_key).unwrap() > max_count { | |
| return false; | |
| } | |
| return true; | |
| } | |
| fn format_currency(&self) -> f64 { | |
| let amount_str = self.load_amount.replace("$", ""); | |
| amount_str.parse::<f64>().unwrap() | |
| } | |
| fn get_week_transaction_ref(&self) -> String { | |
| let ts: DateTime<Utc> = self.time.parse().unwrap(); | |
| let year = ts.iso_week().year(); | |
| let week = ts.iso_week().week(); | |
| let unique_key = format!("{}_{}", year, week); | |
| unique_key | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment