mocklogger/logger/
builder.rs

1// Author: D.S. Ljungmark <spider@skuggor.se>, Modio AB
2// SPDX-License-Identifier: AGPL-3.0-or-later
3use super::LogErr;
4use super::Logger;
5use crate::timefail::Timefail;
6use modio_logger_db::{Datastore, SqlitePool};
7
8pub struct Builder {
9    ds: Option<Datastore>,
10    development: bool,
11}
12
13impl Builder {
14    /// New builder
15    #[must_use]
16    pub const fn new() -> Self {
17        Self {
18            ds: None,
19            development: false,
20        }
21    }
22    /// Set the datastore
23    ///
24    /// If this is not called, it will use a temporary datastore
25    #[must_use]
26    pub fn datastore(mut self, ds: Datastore) -> Self {
27        self.ds = Some(ds);
28        self
29    }
30
31    /// Set the datastore from a pool
32    ///
33    /// Replaces the datastore with one based from the pool
34    pub async fn datastore_pool(mut self, p: &SqlitePool) -> Self {
35        let pool = p.clone();
36        let ds = Datastore::new(pool)
37            .await
38            .expect("Failed to make datastore");
39        self.ds = Some(ds);
40        self
41    }
42
43    /// Set development mode to true/false
44    ///
45    /// default is false
46    #[must_use]
47    pub const fn development(mut self, val: bool) -> Self {
48        self.development = val;
49        self
50    }
51
52    pub async fn build(self) -> Result<Logger, LogErr> {
53        let tf = if self.development {
54            Timefail::development()
55        } else {
56            Timefail::default()
57        };
58
59        let datastore = if let Some(ds) = self.ds {
60            ds
61        } else {
62            Datastore::temporary().await
63        };
64        let logger = Logger::new(tf, datastore).await?;
65        Ok(logger)
66    }
67}
68
69impl Default for Builder {
70    fn default() -> Self {
71        Self::new()
72    }
73}