rec23-rs 0.2.82

A library for REC23 CRM.
Documentation
use std::error::Error;
use bb8_postgres::bb8::Pool;
use bb8_postgres::PostgresConnectionManager;
use bb8_postgres::tokio_postgres::{GenericClient, NoTls, Row};
use paperclip::actix::Apiv2Schema;
use serde::{Deserialize, Serialize};

const GET_DEPT_BY_ID: &str = "SELECT dept.id, dept.name, dept_chat.chat_id FROM rec23.dept dept LEFT JOIN rec23.dept_chat dept_chat ON dept_chat.dept_id = dept.id WHERE dept.id = $1";
const GET: &str = "SELECT dept.id, dept.name, dept_chat.chat_id FROM rec23.dept dept LEFT JOIN rec23.dept_chat dept_chat ON dept_chat.dept_id = dept.id";

#[derive(Serialize, Deserialize, Apiv2Schema)]
pub struct Dept {
    pub id: i32,
    pub name: String,
    pub chat_id: Option<i32>,
}

impl Dept {
    pub async fn get(pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<Vec<Self>, Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let rows = connection.query(GET, &[]).await?;
        Ok(rows.iter().map(|row| Self::convert_from_row(row)).collect())
    }

    pub async fn get_by_id(id: i32, pool: &Pool<PostgresConnectionManager<NoTls>>) -> Result<Option<Self>, Box<dyn Error + Sync + Send>> {
        let connection = pool.get().await?;
        let client = connection.client();
        return match client.query_opt(GET_DEPT_BY_ID, &[&id]).await? {
            Some(value) => Ok(Some(Self::convert_from_row(&value))),
            None => Ok(None)
        };
    }

    pub fn convert_from_row(row: &Row) -> Self {
        Self {
            id: row.get("id"),
            name: row.get("name"),
            chat_id: row.get("chat_id"),
        }
    }
}