articles_rs/articles/
service.rs

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
use chrono::{DateTime, Utc};
use sqlx::postgres::PgPool;
use std::collections::HashMap;
use std::error;
use std::io::ErrorKind;

use uuid::Uuid;

use crate::postgres_repository::PostgresRepository;

use super::{config::DbConfig, Article, ArticleRepository};

pub struct ArticleService {
    repo: ArticleRepository,
}

impl std::fmt::Debug for ArticleService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArticleService")
            .field("repo", &"ArticleRepository")
            .finish()
    }
}

impl ArticleService {
    pub async fn new(config: DbConfig) -> Self {
        let url = &config.get_connection_url();
        let pool = PgPool::connect(url)
            .await
            .expect("unable to connect to the database");
        let repo = ArticleRepository::new(pool);

        ArticleService { repo }
    }

    pub async fn get_article_by_id(&self, id: Uuid) -> Result<Article, Box<dyn error::Error>> {
        match self.repo.find_by_id(id).await {
            Ok(Some(article)) => Ok(article),
            Ok(None) => Err(Box::new(std::io::Error::new(
                ErrorKind::NotFound,
                "Article not found",
            ))),
            Err(e) => Err(Box::new(e)),
        }
    }

    pub async fn delete_article(&self, id: Uuid) -> Result<(), Box<dyn error::Error>> {
        match self.repo.delete(id).await {
            Ok(_) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }

    pub async fn list_articles(
        &self,
        filter: Option<HashMap<String, String>>,
    ) -> Result<Vec<Article>, Box<dyn error::Error>> {
        match self.repo.list(filter).await {
            Ok(v) => Ok(v),
            Err(e) => Err(Box::new(e)),
        }
    }

    pub async fn create_article(
        &self,
        title: &str,
        slug: &str,
        description: &str,
        author: &str,
    ) -> Result<Uuid, Box<dyn error::Error>> {
        let article = Article::new(title, slug, description, author);

        match self.repo.create(&article).await {
            Ok(id) => Ok(id),
            Err(e) => Err(Box::new(e)),
        }
    }

    pub async fn update_article(
        &self,
        id: Uuid,
        title: &str,
        slug: &str,
        description: &str,
        author: &str,
        status: Option<&str>,
        date: Option<DateTime<Utc>>,
        contents: &str,
    ) -> Result<(), Box<dyn error::Error>> {
        let mut article = self
            .repo
            .find_by_id(id)
            .await?
            .ok_or_else(|| std::io::Error::new(ErrorKind::NotFound, "Article not found"))?;

        article.title = title.to_string();
        article.slug = slug.to_string();
        article.description = description.to_string();
        article.author = author.to_string();
        article.content = contents.to_string();

        if let Some(s) = status {
            article.status = s.to_string();
        }
        if let Some(d) = date {
            article.date = d;
        }

        match self.repo.update(&article).await {
            Ok(_) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }
}