From eb480e47cbee42f0d20fc6edebd2270dbbb72f54 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Fri, 1 Apr 2022 01:21:40 -0700 Subject: feat: variable max amount of comments --- examples/windmark_comments.rs | 2 ++ src/lib.rs | 21 +++++++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/examples/windmark_comments.rs b/examples/windmark_comments.rs index bfe6bed..fd7d266 100644 --- a/examples/windmark_comments.rs +++ b/examples/windmark_comments.rs @@ -20,6 +20,8 @@ use windmark::Response; #[windmark::main] async fn main() -> Result<(), Box> { + windmark_comments::set_max_comments(10); + windmark::Router::new() .set_private_key_file("windmark_comments_private.pem") .set_certificate_file("windmark_comments_public.pem") diff --git a/src/lib.rs b/src/lib.rs index ad031d1..c5b1016 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -79,13 +79,20 @@ #![deny(clippy::all, clippy::nursery, clippy::pedantic)] #![recursion_limit = "128"] -use std::{lazy::SyncLazy, sync::Mutex}; +use std::{ + lazy::SyncLazy, + sync::{ + atomic::{AtomicUsize, Ordering}, + Mutex, + }, +}; use chrono::{DateTime, Utc}; use windmark::Response; static COMMENTS: SyncLazy> = SyncLazy::new(|| Mutex::new(vec![])); +static MAX_COMMENTS: AtomicUsize = AtomicUsize::new(500); /// Keeps track of comments, storing date/ time and the comment. pub type Comments = Vec<(DateTime, String)>; @@ -99,6 +106,11 @@ pub fn get_comments() -> Result> { Ok((*COMMENTS.lock()?).clone()) } +/// Set the max amount of comments. +pub fn set_max_comments(max_comments: usize) { + MAX_COMMENTS.store(max_comments, Ordering::SeqCst); +} + /// The Windmark Comments module. /// /// # Mounts @@ -120,11 +132,12 @@ pub fn module(router: &mut windmark::Router) { |query| { if let Ok(comment) = urlencoding::decode(query) { if let Ok(mut comments) = COMMENTS.lock() { - if comments.len() >= 500 { + if comments.len() >= MAX_COMMENTS.load(Ordering::SeqCst) { Response::Success(format!( "Your comment, \"{}\", could not be posted as the instance \ - comment limit (500) has been met...", - comment + comment limit ({}) has been met...", + comment, + MAX_COMMENTS.load(Ordering::SeqCst) )) } else { (*comments).push((Utc::now(), comment.to_string())); -- cgit v1.2.3