json_placeholder_data/posts/
mod.rs

1use crate::{by_id, from_json};
2use serde::{Deserialize, Serialize};
3use serde_with::skip_serializing_none;
4
5const PLACEHOLDER_JSON_POSTS: &str = include_str!("posts.json");
6
7#[skip_serializing_none]
8#[derive(Deserialize, Serialize)]
9pub struct Post {
10    pub id: Option<i32>,
11    pub title: String,
12    pub body: String,
13    #[serde(rename = "userId")]
14    pub user_id: Option<i32>,
15}
16
17impl std::fmt::Display for Post {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        write!(f, "Post: title = {}", self.title)
20    }
21}
22
23/// Get all the posts available
24///
25/// # Example
26/// ```
27/// use json_placeholder_data::posts::get_all;
28/// assert_eq!(get_all().len(), 100);
29/// ```
30pub fn get_all() -> Vec<Post> {
31    from_json!(PLACEHOLDER_JSON_POSTS)
32}
33
34/// Get a post by id
35///
36/// # Example
37/// ```
38/// use json_placeholder_data::posts::get;
39/// assert_eq!(
40///     get(1).title.as_str(),
41///     "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
42/// );
43/// ```
44pub fn get(id: i32) -> Post {
45    by_id!(id)
46}