laravel-comments 0.2.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
//! Comments for [Laravel Rust](https://crates.io/crates/laravel-rust) models: threaded replies
//! on [`laravel-nestedset`](https://crates.io/crates/laravel-nestedset), moderation, reactions,
//! and events, read without N+1 queries.
//!
//! Register the provider in `src/app.rs`, run `laravel migrate`, and declare the comment model
//! with [`comment_model!`]:
//!
//! ```no_run
//! use laravel::Application;
//!
//! # let _ =
//! Application::configure().with_providers(|providers| {
//!     providers.add(laravel_comments::CommentsServiceProvider::new());
//! })
//! # ;
//! ```
//!
//! See the README for a walkthrough.

pub mod abilities;
mod author;
mod config;
mod error;
pub mod events;
#[cfg(feature = "markdown")]
pub mod markdown;
mod mentions;
mod model;
mod moderation;
mod ops;
mod reactions;
mod revisions;
mod schema;
mod status;
mod thread;
mod throttle;

use std::future::Future;

use laravel::config::{Config, Env};
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

pub use crate::author::{Author, Commenter};
pub use crate::config::{AutoApprove, BroadcastChannel, CommentsConfig, UnknownAutoApprove, UnknownBroadcastChannel};
pub use crate::error::CommentError;
pub use crate::mentions::{CommentMention, mentions};
pub use crate::model::{CommentColumns, CommentModel, CommentRow};
pub use crate::moderation::NewComment;
pub use crate::reactions::{CommentReaction, reaction_counts, reactions_of};
pub use crate::revisions::CommentRevision;
pub use crate::schema::CommentsBlueprint;
pub use crate::status::{Status, Visibility};
pub use crate::thread::{Sort, ThreadNode, ThreadPage, Threads};
pub use crate::throttle::throttle;

use crate::mentions::MentionRule;
use crate::moderation::ModerationRule;

#[doc(hidden)]
pub mod __private {
    pub use {laravel, laravel_nestedset};
}

/// Adds the package's settings, its migrations, and the application's moderation and mention
/// rules.
#[derive(Clone, Default)]
pub struct CommentsServiceProvider {
    rule: Option<ModerationRule>,
    mentions: MentionRule,
}

impl CommentsServiceProvider {
    /// A provider that gives new comments the status `COMMENTS_AUTO_APPROVE` says.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Gives each new comment the status `rule` returns, instead of `COMMENTS_AUTO_APPROVE`: a
    /// place for trusted authors, banned words, or a spam check.
    ///
    /// ```no_run
    /// use laravel_comments::{CommentsServiceProvider, NewComment, Status};
    ///
    /// let provider = CommentsServiceProvider::new().moderate_with(async |comment: NewComment| {
    ///     if comment.body.contains("casino") {
    ///         return Ok(Status::Spam);
    ///     }
    ///     Ok(if comment.author_id.is_some() { Status::Approved } else { Status::Pending })
    /// });
    /// ```
    #[must_use]
    pub fn moderate_with<F, Fut>(mut self, rule: F) -> Self
    where
        F: Fn(NewComment) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = laravel::Result<Status>> + Send + 'static,
    {
        self.rule = Some(ModerationRule::new(rule));
        self
    }

    /// Turns `@name` mentions on: `rule` gets the names a comment mentions, lowercased, and
    /// returns the keys of the users they name. Each mentioned user gets one
    /// [`UserMentioned`](crate::events::UserMentioned) once the comment is visible.
    ///
    /// ```no_run
    /// # use laravel::model::model;
    /// # #[model] pub struct User { pub id: i64, pub username: String }
    /// use laravel_comments::CommentsServiceProvider;
    ///
    /// let provider = CommentsServiceProvider::new().mentions_with(async |names: Vec<String>| {
    ///     User::query().filter(User::username.is_in(names)).pluck(User::id).await
    /// });
    /// ```
    #[must_use]
    pub fn mentions_with<F, Fut>(mut self, rule: F) -> Self
    where
        F: Fn(Vec<String>) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = laravel::Result<Vec<i64>>> + Send + 'static,
    {
        self.mentions = MentionRule::new(rule);
        self
    }
}

impl ServiceProvider for CommentsServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    fn register(&self, app: &mut Registrar) {
        app.migrations().add(laravel::db::migrations!("database/migrations"));
        app.instance(self.rule.clone().unwrap_or(ModerationRule(None)));
        app.instance(self.mentions.clone());
    }
}