Skip to main content

serenade_mailer/
compile_pass.rs

1//! DI tag and compile pass for the default mailer transport.
2
3use std::sync::Arc;
4
5use serenade_di::{CompilePass, ContainerBuilder, DiError, ServiceDefinition};
6
7use crate::{NullTransport, Transport};
8
9/// Service tag applied to mail transport definitions.
10pub const MAILER_TRANSPORT_TAG: &str = "mailer.transport";
11
12/// Container id of the default mailer when registered by the pass.
13pub const DEFAULT_MAILER_SERVICE: &str = "mailer";
14
15/// Newtype so transport trait objects can be stored in the container.
16#[derive(Clone)]
17pub struct MailerService(pub Arc<dyn Transport>);
18
19impl MailerService {
20    /// Sends through the wrapped transport.
21    ///
22    /// # Errors
23    ///
24    /// Propagates [`crate::MailerError`] from the transport.
25    pub fn send(&self, email: &crate::Email) -> Result<(), crate::MailerError> {
26        self.0.send(email)
27    }
28}
29
30/// Seeds [`DEFAULT_MAILER_SERVICE`] with a [`NullTransport`] when missing.
31#[derive(Debug, Default)]
32pub struct RegisterDefaultMailerPass;
33
34impl CompilePass for RegisterDefaultMailerPass {
35    fn name(&self) -> &'static str {
36        "register_default_mailer"
37    }
38
39    fn process(&self, builder: &mut ContainerBuilder) -> Result<(), DiError> {
40        let has_default = builder
41            .definitions()
42            .iter()
43            .any(|definition| definition.id() == DEFAULT_MAILER_SERVICE);
44        if has_default {
45            return Ok(());
46        }
47
48        builder.register(
49            ServiceDefinition::new(DEFAULT_MAILER_SERVICE).with_tag(MAILER_TRANSPORT_TAG),
50            |_container| {
51                Ok(Box::new(MailerService(
52                    Arc::new(NullTransport::new()) as Arc<dyn Transport>
53                )))
54            },
55        )
56    }
57}