markdown_parser/adapt/
mod.rs

1//! enable feature `adapt` to use this module
2//!
3//! adapt mod will help to transform the format of a Markdown's front matters
4
5mod json;
6mod toml;
7mod yaml;
8
9use crate::{error::Error, Format, Markdown};
10
11pub use self::json::JsonAdapter;
12pub use self::toml::TomlAdapter;
13pub use self::yaml::YamlAdapter;
14
15/// MDAdapter trait
16/// can transform the format of a Markdown into the given kind
17pub trait Adapter {
18    fn adapt<T>(&self, md: Markdown) -> crate::MarkdownResult
19    where
20        T: serde::ser::Serialize + serde::de::DeserializeOwned;
21
22    fn ser_fm<T>(&self, data: &T) -> Result<String, Error>
23    where
24        T: serde::ser::Serialize;
25}
26
27/// parse front matter into any struct
28///
29/// just deserialize it
30pub fn de_fm<T>(md: &Markdown) -> Result<T, Error>
31where
32    T: serde::de::DeserializeOwned,
33{
34    let fm = md.front_matter();
35
36    match md.format() {
37        Format::YAML => {
38            let data = serde_yaml::from_str::<T>(&fm)?;
39
40            return Ok(data);
41        }
42        Format::TOML => {
43            let data = ::toml::from_str::<T>(&fm)?;
44
45            return Ok(data);
46        }
47        Format::JSON => {
48            let data = serde_json::from_str::<T>(&fm)?;
49
50            return Ok(data);
51        }
52    }
53}
54
55/// the all optional format of front matters
56///
57/// even if unexpected data is given
58///
59/// it will safely return an none struct
60#[derive(serde::Serialize, serde::Deserialize, Debug)]
61pub struct BasicObject {
62    date: Option<String>,
63    /// required field
64    title: Option<String>,
65    /// optional field
66    tags: Option<Vec<String>>,
67    /// optional field
68    categories: Option<Vec<String>>,
69}
70
71#[derive(serde::Serialize, serde::Deserialize, Debug)]
72/// empty object
73///
74/// using it for test reason
75pub struct EmptyObject {}