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
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! Article service module for managing articles and their associated images
//! 
//! This module provides the main service layer for interacting with articles,
//! handling both article data and associated image operations through repositories.

use chrono::{DateTime, Utc};
use sqlx::postgres::PgPool;
use std::collections::HashMap;
use std::error;
use std::io::ErrorKind;

use uuid::Uuid;

use crate::{
    article_repository::{ArticleRepository, DbArticle},
    config::DbConfig,
    images_repository::{DbArticleImage, ImageRepository},
    postgres_repository::PostgresRepository,
};

use super::{Article, ArticleKind};

/// Service for managing articles and their associated images
///
/// Provides high-level operations for creating, reading, updating and deleting articles,
/// while also handling associated image management.
pub struct ArticleService {
    article_repo: ArticleRepository,
    image_repo: ImageRepository,
}

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

impl ArticleService {
    /// Creates a new ArticleService instance
    ///
    /// # Arguments
    /// * `config` - Database configuration containing connection details
    ///
    /// # Returns
    /// A new ArticleService instance with initialized repositories
    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 article_repo = ArticleRepository::new(pool.clone());
        let image_repo = ImageRepository::new(pool);

        ArticleService {
            article_repo,
            image_repo,
        }
    }

    /// Retrieves an article with its associated images
    ///
    /// # Arguments
    /// * `article` - The database article to fetch images for
    ///
    /// # Returns
    /// The article with its associated images loaded
    async fn get_article_with_images(
        &self,
        article: DbArticle,
    ) -> Result<Article, Box<dyn error::Error>> {
        let mut filter = HashMap::new();
        filter.insert(
            "article_id".to_string(),
            article.id.expect("could not get id").to_string(),
        );
        let images = self.image_repo.list(Some(filter)).await?;
        let image_paths: Vec<String> = images.into_iter().map(|img| img.image_path).collect();

        let mut found = Article::from(article);
        found.add_images(image_paths);
        Ok(found)
    }

    /// Retrieves an article by its slug
    ///
    /// # Arguments
    /// * `slug` - The URL-friendly slug identifying the article
    ///
    /// # Returns
    /// The article if found, otherwise an error
    pub async fn get_article_by_slug(&self, slug: &str) -> Result<Article, Box<dyn error::Error>> {
        match self.article_repo.find_by_name(slug.to_string()).await {
            Ok(Some(article)) => self.get_article_with_images(article).await,
            Ok(None) => Err(Box::new(std::io::Error::new(
                ErrorKind::NotFound,
                "Article not found",
            ))),
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Retrieves an article by its ID
    ///
    /// # Arguments
    /// * `id` - The UUID of the article
    ///
    /// # Returns
    /// The article if found, otherwise an error
    pub async fn get_article_by_id(&self, id: Uuid) -> Result<Article, Box<dyn error::Error>> {
        match self.article_repo.find_by_id(id).await {
            Ok(Some(article)) => self.get_article_with_images(article).await,
            Ok(None) => Err(Box::new(std::io::Error::new(
                ErrorKind::NotFound,
                "Article not found",
            ))),
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Deletes an article and its associated images
    ///
    /// # Arguments
    /// * `id` - The UUID of the article to delete
    ///
    /// # Returns
    /// Ok(()) if successful, otherwise an error
    pub async fn delete_article(&self, id: Uuid) -> Result<(), Box<dyn error::Error>> {
        let mut filter = HashMap::new();
        filter.insert("article_id".to_string(), id.to_string());
        self.image_repo.delete_all(Some(filter)).await?;

        match self.article_repo.delete(id).await {
            Ok(_) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Lists articles based on optional filters
    ///
    /// # Arguments
    /// * `filter` - Optional HashMap of filter criteria
    ///
    /// # Returns
    /// Vector of articles matching the filter criteria
    pub async fn list_articles(
        &self,
        filter: Option<HashMap<String, String>>,
    ) -> Result<Vec<Article>, Box<dyn error::Error>> {
        match self.article_repo.list(filter).await {
            Ok(v) => {
                let articles = v.into_iter().map(Article::from).collect();
                Ok(articles)
            }
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Creates a new article
    ///
    /// # Arguments
    /// * `title` - Article title
    /// * `slug` - URL-friendly slug
    /// * `description` - Article description
    /// * `author` - Author string (can be comma-separated or array format)
    /// * `kind` - Optional article type
    ///
    /// # Returns
    /// The UUID of the created article
    pub async fn create_article(
        &self,
        title: &str,
        slug: &str,
        description: &str,
        author: &str,
        kind: Option<ArticleKind>,
    ) -> Result<Uuid, Box<dyn error::Error>> {
        let authors = if author.contains('[') && author.contains(']') {
            author
                .trim_matches(|c| c == '[' || c == ']')
                .split(',')
                .map(|s| {
                    s.trim_matches('\'')
                        .trim()
                        .trim_matches('(')
                        .trim_matches(')')
                })
                .collect::<Vec<&str>>()
        } else {
            author
                .split(',')
                .map(|s| s.trim().trim_matches('(').trim_matches(')'))
                .collect::<Vec<&str>>()
        };

        let mut article = Article::new(title, slug, description, authors);
        if let Some(k) = kind {
            article.kind = k;
        }
        match self.article_repo.create(&DbArticle::from(article)).await {
            Ok(id) => Ok(id),
            Err(e) => Err(Box::new(e)),
        }
    }

    /// Updates an existing article and its associated images
    ///
    /// # Arguments
    /// * `id` - Article UUID
    /// * `title` - New title
    /// * `slug` - New slug
    /// * `description` - New description
    /// * `author` - New author list
    /// * `status` - Optional new status
    /// * `created` - Optional new creation date
    /// * `contents` - New content
    /// * `images` - New list of image paths
    /// * `source` - New source
    /// * `publish` - Optional new publish date
    /// * `kind` - Optional new article type
    ///
    /// # Returns
    /// Ok(()) if successful, otherwise an error
    pub async fn update_article(
        &self,
        id: Uuid,
        title: &str,
        slug: &str,
        description: &str,
        author: Vec<String>,
        status: Option<&str>,
        created: Option<DateTime<Utc>>,
        contents: &str,
        images: Vec<String>,
        source: &str,
        publish: Option<DateTime<Utc>>,
        kind: Option<ArticleKind>,
    ) -> Result<(), Box<dyn error::Error>> {
        let mut article = self
            .article_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.join(",");
        article.content = contents.to_string();
        article.source = source.to_string();

        if let Some(s) = status {
            article.status = s.to_string();
        }
        if let Some(d) = created {
            article.created = d;
        }
        if let Some(p) = publish {
            article.published = Some(p);
        }
        if let Some(k) = kind {
            article.kind = match k {
                ArticleKind::POST => String::from(""),
                ArticleKind::LINK => String::from("LINK"),
            };
        }

        self.article_repo.update(&article).await?;
        let mut filter = HashMap::new();
        filter.insert("article_id".to_string(), id.to_string());
        let current_images = self.image_repo.list(Some(filter)).await?;
        let current_paths: Vec<String> = current_images
            .iter()
            .map(|img| img.image_path.clone())
            .collect();

        // Add new images
        for image_path in &images {
            if !image_path.is_empty() && !current_paths.contains(image_path) {
                let image = DbArticleImage {
                    id: None,
                    article_id: id,
                    image_path: image_path.clone(),
                    visible: true,
                    created_at: Utc::now(),
                };
                self.image_repo.create(&image).await?;
            }
        }

        // Remove images not in new list
        for current_image in current_images {
            if !images.contains(&current_image.image_path) {
                self.image_repo.delete(current_image.id.unwrap()).await?;
            }
        }

        Ok(())
    }
}