summaryrefslogtreecommitdiff
path: root/src/branch/models.rs
blob: c8a8d6561a349bcb1b7f3300489026313e124bed (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use crate::db::get_client;
use crate::errors::{AppError, AppErrorType};

use deadpool_postgres::Pool;
use serde::{Deserialize, Serialize};
use tokio_pg_mapper::FromTokioPostgresRow;
use tokio_pg_mapper_derive::PostgresMapper;
use uuid::Uuid;

#[derive(Serialize, Deserialize, PostgresMapper)]
#[pg_mapper(table = "branch")]
/// Branch model
pub struct Branch {
    pub id: Uuid,
    pub name: String,
    pub repository_id: Uuid,
    pub head: String,
}

/// Struct used for forms
pub struct BranchData {
    pub name: String,
    pub repository_id: Uuid,
    pub head: String,
}

impl Branch {
    /// Find all branches
    pub async fn find_all(pool: Pool) -> Result<Vec<Branch>, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client.prepare("SELECT * FROM branch").await?;

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

        Ok(branches)
    }

    /// Find a branch with an `id` equals to an Uuid element
    pub async fn find(pool: Pool, id: &Uuid) -> Result<Branch, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement =
            client.prepare("SELECT * FROM branch WHERE id = $1").await?;

        let branch = client
            .query_opt(&statement, &[&id])
            .await?
            .map(|row| Branch::from_row_ref(&row).unwrap());

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

    /// Find all branches of a repository
    pub async fn find_by_repo(
        pool: Pool,
        repo: &Uuid,
    ) -> Result<Vec<Branch>, AppError> {
        let client = get_client(pool.clone()).await.unwrap();
        let statement = client
            .prepare("SELECT * FROM branch WHERE repository_id=$1")
            .await?;

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

        Ok(branches)
    }

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

        let branch = client
            .query_opt(&statement, &[&id])
            .await?
            .map(|row| Branch::from_row_ref(&row).unwrap());

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

    /// Create a new branch
    pub async fn create(
        pool: Pool,
        data: &BranchData,
    ) -> Result<Branch, AppError> {
        let client = get_client(pool.clone()).await.unwrap();

        let statement = client
            .prepare(
                "INSERT INTO repository(id, name, repository_id, head)
                VALUES($1, $2, $3, $4)
                RETURNING *",
            )
            .await?;

        // Create a new UUID v4
        let uuid = Uuid::new_v4();

        let branch = client
            .query_opt(
                &statement,
                &[&uuid, &data.name, &data.repository_id, &data.head],
            )
            .await?
            .map(|row| Branch::from_row_ref(&row).unwrap());

        match branch {
            Some(branch) => Ok(branch),
            None => Err(AppError {
                message: Some("Error creating a new branch".to_string()),
                cause: Some("Unknown error".to_string()),
                error_type: AppErrorType::DbError,
            }),
        }
    }
}