use crate::model::Model;
use larust_core::AppError;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU64, Ordering};
static SEQUENCE: AtomicU64 = AtomicU64::new(1);
fn next_seq() -> u64 {
SEQUENCE.fetch_add(1, Ordering::Relaxed)
}
pub trait Factory: Sized + 'static {
type Model: Model;
fn definition(seq: u64) -> <Self::Model as Model>::New;
fn new() -> FactoryBuilder<Self> {
FactoryBuilder::new()
}
}
type StateFn<F> = Box<
dyn Fn(<<F as Factory>::Model as Model>::New) -> <<F as Factory>::Model as Model>::New
+ Send
+ Sync,
>;
pub struct FactoryBuilder<F: Factory> {
states: Vec<StateFn<F>>,
_marker: PhantomData<fn() -> F>,
}
impl<F: Factory> FactoryBuilder<F> {
pub fn new() -> Self {
Self {
states: Vec::new(),
_marker: PhantomData,
}
}
#[must_use]
pub fn state(
mut self,
f: impl Fn(<F::Model as Model>::New) -> <F::Model as Model>::New + Send + Sync + 'static,
) -> Self {
self.states.push(Box::new(f));
self
}
pub fn make(&self) -> <F::Model as Model>::New {
let mut data = F::definition(next_seq());
for state in &self.states {
data = state(data);
}
data
}
pub fn make_many(&self, n: usize) -> Vec<<F::Model as Model>::New> {
(0..n).map(|_| self.make()).collect()
}
pub async fn create(&self) -> Result<F::Model, AppError> {
F::Model::create(self.make()).await
}
pub async fn create_many(&self, n: usize) -> Result<Vec<F::Model>, AppError> {
let mut out = Vec::with_capacity(n);
for _ in 0..n {
out.push(self.create().await?);
}
Ok(out)
}
}
impl<F: Factory> Default for FactoryBuilder<F> {
fn default() -> Self {
Self::new()
}
}