Skip to main content

capy_testing/
factory.rs

1use capy_core::Result;
2use sea_orm::ConnectionTrait;
3use std::future::Future;
4
5/// An application-owned record builder. Implement with native SeaORM operations.
6/// Passing a borrowed connection permits both a pool and an existing transaction.
7pub trait Factory: Sized {
8    /// The record produced by this factory, usually an application model.
9    type Model;
10
11    /// Insert through the supplied connection; never acquire a different pool internally.
12    fn create<C: ConnectionTrait>(
13        self,
14        connection: &C,
15    ) -> impl Future<Output = Result<Self::Model>> + Send;
16}
17
18/// A factory and its explicit database/transaction. Own field defaults in application code.
19pub struct FactoryBuilder<'a, F, C> {
20    factory: F,
21    connection: &'a C,
22}
23
24impl<'a, F: Factory, C: ConnectionTrait> FactoryBuilder<'a, F, C> {
25    /// Bind an application factory to a database or transaction.
26    pub fn new(factory: F, connection: &'a C) -> Self {
27        Self {
28            factory,
29            connection,
30        }
31    }
32
33    /// Customize ordinary Rust fields or invoke application-owned builder methods.
34    pub fn with(mut self, customize: impl FnOnce(&mut F)) -> Self {
35        customize(&mut self.factory);
36        self
37    }
38
39    /// Create the record in the selected database/transaction.
40    pub async fn create(self) -> Result<F::Model> {
41        self.factory.create(self.connection).await
42    }
43}