hacker_rs/
comments.rs

1//! Stories listed on the Hacker News homepage and all associated data.
2
3use time::OffsetDateTime;
4
5use crate::{
6    errors::HackerNewsClientError,
7    items::{HackerNewsItem, HackerNewsItemType},
8    HackerNewsID,
9};
10
11/// Represents a Hacker News story and all associated data to it including author, text, and child comments.
12#[derive(Debug)]
13pub struct HackerNewsComment {
14    /// The item's unique id.
15    pub id: HackerNewsID,
16    /// A list of associated child comment IDs.
17    pub sub_comments: Vec<HackerNewsID>,
18    /// Creation date of the comment.
19    pub created_at: OffsetDateTime,
20    /// The ID of the parent story.
21    pub parent_story: HackerNewsID,
22    /// Content of the comment.
23    pub text: String,
24    /// Username of the comment poster.
25    pub by: String,
26}
27
28impl TryFrom<HackerNewsItem> for HackerNewsComment {
29    type Error = HackerNewsClientError;
30
31    fn try_from(item: HackerNewsItem) -> Result<Self, Self::Error> {
32        if item.get_item_type() != HackerNewsItemType::Comment {
33            return Err(HackerNewsClientError::InvalidTypeMapping(
34                item.get_item_type(),
35            ));
36        }
37
38        Ok(Self {
39            id: item.id,
40            sub_comments: item.kids.unwrap_or_default(),
41            created_at: item.created_at,
42            parent_story: item.parent.unwrap_or_default(),
43            text: item.text.unwrap_or_default(),
44            by: item.by.unwrap_or_default(),
45        })
46    }
47}