aboutsummaryrefslogtreecommitdiffstats
path: root/src/posts.rs
blob: a8e9f90c494bc5b848ae0225bdad596f4759845a (plain) (blame)
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
use std::collections::HashSet;

use chrono::{DateTime, Utc};
use serde::Serialize;

#[derive(Serialize, Debug)]
pub enum PostType {
    Article,
    Note,
}

pub trait Post {
    fn id(&self) -> &str;
    fn subject(&self) -> Option<&str>;
    fn published_at(&self) -> &DateTime<Utc>;
    fn updated_at(&self) -> Option<&DateTime<Utc>>;
    fn tags(&self) -> &Vec<String>;
    fn lang(&self) -> &str;
    fn post_type(&self) -> PostType;
    fn content(&self) -> &str;

    fn link(&self) -> String {
        "https://en.blos.sm/posts/".to_owned() + self.id()
    }

    fn get_tags<'a>(posts: &'a Vec<Self>) -> Vec<&'a String>
    where
        Self: Sized,
    {
        let mut tags = posts
            .into_iter()
            .fold(HashSet::new(), |mut acc, post| {
                let tags = post.tags();
                for tag in tags {
                    acc.insert(tag);
                }
                acc
            })
            .into_iter()
            .collect::<Vec<_>>();
        tags.sort();
        tags
    }

    fn filter_by_tags(posts: Vec<Self>, filter_tags: &HashSet<String>) -> Vec<Self>
    where
        Self: Sized,
    {
        posts
            .into_iter()
            .filter(|post| {
                for tag in post.tags() {
                    match filter_tags.contains(tag) {
                        true => return true,
                        false => continue,
                    }
                }
                false
            })
            .collect()
    }
}