laravel-comments 0.3.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! A rate limit for posting.

use std::net::IpAddr;

use laravel::rate_limit::{self, Limit};

use crate::author::{Author, Commenter};
use crate::ops;

/// Counts a comment by `author` against `COMMENTS_RATE_LIMIT` comments a minute: users by their
/// key, guests by `ip`. Fails with [`TooManyAttempts`](laravel::rate_limit::TooManyAttempts),
/// a `429` response with `Retry-After`, once the author posted too many.
///
/// ```no_run
/// # use laravel::model::model;
/// # use laravel_comments::{Author, Commenter};
/// # #[model] pub struct User { pub id: i64 }
/// # impl Commenter for User { fn commenter_id(&self) -> i64 { self.id } }
/// # async fn example(user: User, request: laravel::http::Request) -> laravel::Result<()> {
/// laravel_comments::throttle(Author::user(&user), request.ip()).await?;
/// // Post the comment...
/// # Ok(()) }
/// ```
///
/// # Errors
///
/// Fails when the author is over the limit, or when the cache fails.
pub async fn throttle<U: Commenter>(author: Author<'_, U>, ip: IpAddr) -> laravel::Result<()> {
    let per_minute = ops::config().rate_limit;
    if per_minute == 0 {
        return Ok(());
    }
    let key = match author {
        Author::User(user) => format!("comments:user:{}", user.commenter_id()),
        Author::Guest { .. } => format!("comments:ip:{ip}"),
    };
    rate_limit::attempt(&key, Limit::per_minute(per_minute)).await??;
    Ok(())
}