parse_book_source/source/rule/
rule_explore.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
use crate::{
    utils::{json_path, JsonData},
    BookList, BookListItem, ParseError, Result, Variables,
};
use anyhow::anyhow;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleExplore {
    pub author: String,
    pub book_list: String,
    pub book_url: String,
    pub cover_url: String,
    pub intro: String,
    pub kind: String,
    pub name: String,
    pub word_count: String,
}

#[derive(Debug, Clone)]
pub struct JsonRuleExplore {
    pub book_list: String,
    pub author: JsonData,
    pub intro: JsonData,
    pub kind: JsonData,
    pub name: JsonData,
    pub word_count: JsonData,
    pub book_url: JsonData,
    pub cover_url: JsonData,
}

impl TryFrom<&RuleExplore> for JsonRuleExplore {
    type Error = ParseError;
    fn try_from(value: &RuleExplore) -> std::result::Result<Self, Self::Error> {
        Ok(Self {
            book_list: value.book_list.clone(),
            author: value.author.as_str().try_into()?,
            intro: value.intro.as_str().try_into()?,
            kind: value.kind.as_str().try_into()?,
            name: value.name.as_str().try_into()?,
            word_count: value.word_count.as_str().try_into()?,
            book_url: value.book_url.as_str().try_into()?,
            cover_url: value.cover_url.as_str().try_into()?,
        })
    }
}

impl TryFrom<RuleExplore> for JsonRuleExplore {
    type Error = ParseError;
    fn try_from(value: RuleExplore) -> std::result::Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

impl JsonRuleExplore {
    pub fn parse_book_list(&self, data: &Value, variables: &mut Variables) -> Result<BookList> {
        let book_list = if self.book_list.as_str().ends_with("[*]") {
            json_path(data, self.book_list.as_str())?
        } else {
            json_path(data, &format!("{}[*]", self.book_list))?
        };

        let mut res = vec![];
        for item in book_list
            .as_array()
            .ok_or(anyhow!("book_list is not array"))?
        {
            res.push(BookListItem {
                author: self.author.parse_data(item, variables)?,
                intro: self.intro.parse_data(item, variables)?,
                kind: self.kind.parse_data(item, variables)?,
                name: self.name.parse_data(item, variables)?,
                word_count: self.word_count.parse_data(item, variables)?,
                book_url: self.book_url.parse_data(item, variables)?,
                cover_url: self.cover_url.parse_data(item, variables).ok(),
            });
        }

        Ok(res.into())
    }
}