shindo_coding_utils 0.3.9

A utils crates which will be used in various micro-services
Documentation
use async_trait::async_trait;
use sea_orm::*;
use std::sync::Arc;

use crate::types::Experiment;
use crate::schemas::experiment::{self, ActiveModel, Model, Entity};

#[async_trait]
pub trait ExperimentRepository: Send + Sync {
    async fn insert_many(
        &self,
        rows: &Vec<Experiment>,
    ) -> Result<InsertResult<ActiveModel>, DbErr>;

    async fn find_many(&self) -> Result<Vec<Model>, DbErr>;
}

pub struct SeaOrmExperimentRepository {
    db_conn: Arc<DatabaseConnection>,
}

impl SeaOrmExperimentRepository {
    pub fn new(db_conn: Arc<DatabaseConnection>) -> Self {
        Self { db_conn }
    }
}

#[async_trait]
impl ExperimentRepository for SeaOrmExperimentRepository {
    async fn insert_many(
        &self,
        rows: &Vec<Experiment>,
    ) -> Result<InsertResult<ActiveModel>, DbErr> {
        let active_models = rows.iter().map(move |row| {
            let active_model = ActiveModel {
                ticker: Set(row.ticker.clone()),
                reviewed: Set(false),
                json_string: Set(row.json_string.clone()),
                ..Default::default()
            };

            return active_model;
        });

        let res = Entity::insert_many(active_models)
            .exec(&*self.db_conn)
            .await?;
        Ok(res)
    }

    async fn find_many(&self) -> Result<Vec<Model>, DbErr> {
        Entity::find().all(&*self.db_conn).await
    }
}