sfr-server 0.1.2

The server implementation for a Slack App.
Documentation
//! The trait representing the interface that acts as a slash command.

use sfr_core as sc;
use sfr_slack_api as ssa;
use sfr_types as st;

use crate::handler::oauth::{OauthHandler, OauthHandlerTrait};
use crate::{ResponseError, SlashCommandResponse};
use sc::SlashCommandBody;
use ssa::Client as SlackClient;

/// The trait representing the interface that acts as a slash command.
pub trait SlashCommandHandlerTrait: Send + Sync {
    /// Handles [`SlashCommandBody`].
    fn handle_slash_command(
        &self,
        client: &SlackClient,
        body: SlashCommandBody,
    ) -> impl std::future::Future<Output = Result<st::SlashCommandResponse, ResponseError>> + Send;
}

/// The new type to wrap [`SlashCommandHandlerTrait`].
#[derive(Clone)]
pub(crate) struct SlashCommandHandler<T>(T)
where
    T: SlashCommandHandlerTrait;

impl<T> SlashCommandHandler<T>
where
    T: SlashCommandHandlerTrait,
{
    /// The constructor.
    pub fn new(inner: T) -> Self {
        Self(inner)
    }

    /// The wrapper function for a slash command.
    pub fn handle<'a, OH>(
        &'a self,
        client: reqwest::Client,
        oauth: &'a OauthHandler<OH>,
        body: SlashCommandBody,
    ) -> impl std::future::Future<Output = Result<impl axum::response::IntoResponse, ResponseError>>
           + Send
           + 'a
    where
        OH: OauthHandlerTrait,
    {
        tracing::info!("slash command: start to process");

        async move {
            let token = oauth.take_oauth_token_from_team_id(&body.team_id).await?;
            let client = SlackClient::new(client, token);

            let resp: SlashCommandResponse =
                self.0.handle_slash_command(&client, body).await?.into();
            Ok(resp)
        }
    }
}

impl<T> std::ops::Deref for SlashCommandHandler<T>
where
    T: SlashCommandHandlerTrait,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}