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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use anyhow::{anyhow, Result};
use serde_json::Value;
use std::collections::HashMap;

/// Types of property values
/// See https://developers.notion.com/reference/property-value-object
/// > Possible values are "rich_text", "number", "select", "multi_select", "date",
/// > "formula", "relation", "rollup", "title", "people", "files", "checkbox","url",
/// > "email", "phone_number", "created_time", "created_by", "last_edited_time", and "last_edited_by".
#[derive(Debug, PartialEq)]
pub enum NotionPropertyType {
    RichText,
    Number,
    Select,
    MultiSelect,
    Date,
    Formula,
    Relation,
    Rollup,
    Title,
    People,
    Files,
    Checkbox,
    Url,
    Email,
    PhoneNumber,
    CreatedTime,
    CreatedBy,
    LastEditedTime,
    LastEditedBy,
    Other,
}

#[derive(Debug)]
pub struct NotionProperty {
    pub name: String,
    pub property_type: NotionPropertyType,
    pub property_raw_type: String,
}

#[derive(Debug)]
pub struct NotionDatabaseSchema {
    pub properties: HashMap<String, NotionProperty>,
}

pub fn parse_database_schema(database_resp: &Value) -> Result<NotionDatabaseSchema> {
    validate_object_type(database_resp)?;

    let raw_properties = database_resp
        .as_object()
        .and_then(|resp| resp.get("properties"))
        .and_then(|prop| prop.as_object())
        .ok_or_else(|| anyhow!(r#"It must have "properties" object."#))?;

    let properties = raw_properties
        .keys()
        .filter_map(|key| {
            let property = raw_properties.get(key)?.as_object()?;
            let name = property.get("name")?.as_str()?;
            let property_raw_type = property.get("type")?.as_str()?;
            let property_type = match property_raw_type {
                "rich_text" => NotionPropertyType::RichText,
                "number" => NotionPropertyType::Number,
                "select" => NotionPropertyType::Select,
                "multi_select" => NotionPropertyType::MultiSelect,
                "date" => NotionPropertyType::Date,
                "formula" => NotionPropertyType::Formula,
                "relation" => NotionPropertyType::Relation,
                "rollup" => NotionPropertyType::Rollup,
                "title" => NotionPropertyType::Title,
                "people" => NotionPropertyType::People,
                "files" => NotionPropertyType::Files,
                "checkbox" => NotionPropertyType::Checkbox,
                "url" => NotionPropertyType::Url,
                "email" => NotionPropertyType::Email,
                "phone_number" => NotionPropertyType::PhoneNumber,
                "created_time" => NotionPropertyType::CreatedTime,
                "created_by" => NotionPropertyType::CreatedBy,
                "last_edited_time" => NotionPropertyType::LastEditedTime,
                "last_edited_by" => NotionPropertyType::LastEditedBy,
                _ => NotionPropertyType::Other,
            };
            Some((
                name.to_string(),
                NotionProperty {
                    name: name.to_string(),
                    property_raw_type: property_raw_type.to_string(),
                    property_type,
                },
            ))
        })
        .collect::<HashMap<String, NotionProperty>>();

    Ok(NotionDatabaseSchema { properties })
}

fn validate_object_type(database_resp: &Value) -> Result<()> {
    let object_field = database_resp
        .as_object()
        .and_then(|o| o.get("object"))
        .and_then(|o| o.as_str())
        .ok_or_else(|| anyhow!(r#"It must have `"object": "database"`."#.to_string()))?;

    if object_field == "database" {
        Ok(())
    } else {
        Err(anyhow!(
            r#"It must have `"object": "database"`, but was "{}""#,
            object_field
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_object_type() {
        let data = r#"
        {
            "object": "database"
        }
        "#;
        let json = serde_json::from_str(data).unwrap();
        assert!(validate_object_type(&json).is_ok());

        let data = r#"
        {
            "object": "xxx"
        }
        "#;
        let json = serde_json::from_str(data).unwrap();
        assert!(validate_object_type(&json).is_err());

        let data = r#"
        {}
        "#;
        let json = serde_json::from_str(data).unwrap();
        assert!(validate_object_type(&json).is_err());
    }
}