summaryrefslogtreecommitdiff
path: root/src/commit/models.rs
blob: 8b81a1584976d22078aecccb69470a80f6e39b1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use crate::db::get_client;
use crate::errors::{AppError, AppErrorType};

use chrono::{DateTime, Local};
use deadpool_postgres::Pool;
use serde::{Deserialize, Serialize};
use tokio_pg_mapper::FromTokioPostgresRow;
use tokio_pg_mapper_derive::PostgresMapper;

#[derive(Serialize, Deserialize, PostgresMapper)]
#[pg_mapper(table = "commit")]
/// Commit model
pub struct Commit {
    pub hash: String,
    pub tree: Option<String>,
    pub text: String,
    pub date: DateTime<Local>,
    pub author_email: String, // Reference to Email
    pub author_name: String,
    pub committer_email: String, // Reference to Email
    pub committer_name: String,
    pub repository_url: String, // Reference to Repository
}

impl Commit {
    /// Find all commits. Order them by descrescent `date` field
    pub async fn find_all(pool: Pool) -> Result<Vec<Commit>, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare("SELECT * FROM commit ORDER BY date DESC")
            .await?;

        let commits = client
            .query(&statement, &[])
            .await?
            .iter()
            .map(|row| Commit::from_row_ref(row).unwrap())
            .collect::<Vec<Commit>>();

        Ok(commits)
    }

    // Find a commit that it has an hash equals to `hash`
    pub async fn find(pool: Pool, hash: String) -> Result<Commit, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare("SELECT * FROM commit WHERE hash = $1")
            .await?;

        let commit = client
            .query_opt(&statement, &[&hash])
            .await?
            .map(|row| Commit::from_row_ref(&row).unwrap());

        match commit {
            Some(commit) => Ok(commit),
            None => Err(AppError {
                error_type: AppErrorType::NotFoundError,
                cause: None,
                message: Some("Commit not found".to_string()),
            }),
        }
    }

    /// Find a commit and delete it, but before check if "Authorization"
    /// matches with SECRET_KEY
    pub async fn delete(
        pool: Pool,
        hash: &String,
    ) -> Result<Commit, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare(
                "
                DELETE FROM commit
                WHERE hash=$1
                RETURNING *
                ",
            )
            .await?;

        let commit = client
            .query_opt(&statement, &[&hash])
            .await?
            .map(|row| Commit::from_row_ref(&row).unwrap());

        match commit {
            Some(commit) => Ok(commit),
            None => Err(AppError {
                error_type: AppErrorType::NotFoundError,
                cause: None,
                message: Some("Commit not found".to_string()),
            }),
        }
    }
}