Skip to content

A command-line tool to convert handwritten notes to markdown files

feat: made the create_notion_page request dynamic based on the user's database setup

Tejas Raskar126c49e4d8f1
diff --git a/src/clients/notion_client.rs b/src/clients/notion_client.rs
index c70118f..13b1cb5 100644
--- a/src/clients/notion_client.rs
+++ b/src/clients/notion_client.rs
@@ -7,13 +7,13 @@ use notion_client::objects::block::Block;
use reqwest::Client;
use serde::{Deserialize, Serialize};
-use crate::{error::NotedError, notion::converter};
+use crate::{config, error::NotedError, notion::converter};
// Request structs
#[derive(Serialize)]
pub struct NotionRequest {
pub parent: Parent,
- pub properties: Properties,
+ pub properties: serde_json::Map<String, serde_json::Value>,
pub children: Vec<Block>,
}
@@ -22,40 +22,6 @@ pub struct Parent {
pub database_id: String,
}
-#[derive(Serialize)]
-pub struct Properties {
- #[serde(rename = "Doc name")]
- pub name: Title,
-
- #[serde(rename = "Category")]
- pub category: Category,
-}
-
-#[derive(Serialize)]
-pub struct Title {
- pub title: Vec<TextProperty>,
-}
-
-#[derive(Serialize)]
-pub struct TextProperty {
- pub text: Content,
-}
-
-#[derive(Serialize)]
-pub struct Content {
- pub content: String,
-}
-
-#[derive(Serialize)]
-pub struct Category {
- pub multi_select: Vec<SelectOption>,
-}
-
-#[derive(Serialize)]
-pub struct SelectOption {
- pub name: String,
-}
-
// Response Struct
#[derive(Deserialize, Debug)]
pub struct NotionResponse {
@@ -173,7 +139,8 @@ impl NotionClient {
pub async fn create_notion_page(
&self,
title: &str,
- category: &str,
+ title_property_name: &str,
+ properties: &[config::NotionPropertyConfig],
markdown_content: &str,
) -> Result<NotionResponse, NotedError> {
let url = "https://api.notion.com/v1/pages";
@@ -181,24 +148,74 @@ impl NotionClient {
let blocks = converter::Converter::run(&markdown_content, &arena)
.map_err(|e| NotedError::ApiError(e.to_string()))?;
+ let mut props_map = serde_json::Map::new();
+ props_map.insert(
+ title_property_name.to_string(),
+ serde_json::json!(
+ {
+ "title": [
+ {
+ "text":{
+ "content": title
+ }
+ }
+ ]
+ }),
+ );
+
+ for prop_config in properties {
+ let prop_name = &prop_config.name;
+ let prop_type = &prop_config.property_type;
+ let prop_value = &prop_config.default_value;
+
+ let notion_property_value = match prop_type.as_str() {
+ "multi_select" => {
+ if let Some(arr) = prop_value.as_array() {
+ let options: Vec<_> = arr
+ .iter()
+ .map(|val| serde_json::json!({"name": val}))
+ .collect();
+ serde_json::json!({"multi_select": options})
+ } else {
+ continue;
+ }
+ }
+ "select" => serde_json::json!({
+ "select": {
+ "name": prop_value
+ }
+ }),
+ "rich_text" => serde_json::json!({
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {
+ "content": prop_value
+ }
+ }
+ ]
+ }),
+ "number" => serde_json::json!({
+ "number": prop_value
+ }),
+ "date" => serde_json::json!({
+ "date": {
+ "start": prop_value
+ }
+ }),
+ "checkbox" => serde_json::json!({
+ "checkbox": prop_value
+ }),
+ _ => continue,
+ };
+
+ props_map.insert(prop_name.clone(), notion_property_value);
+ }
let request_body = NotionRequest {
parent: Parent {
database_id: self.database_id.clone(),
},
- properties: Properties {
- name: Title {
- title: vec![TextProperty {
- text: Content {
- content: title.to_string(),
- },
- }],
- },
- category: Category {
- multi_select: vec![SelectOption {
- name: category.to_string(),
- }],
- },
- },
+ properties: props_map,
children: blocks,
};
diff --git a/src/config.rs b/src/config.rs
index 792010f..03b7955 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -18,6 +18,8 @@ pub struct NotionConfig {
pub api_key: String,
pub database_id: String,
#[serde(default)]
+ pub title_property_name: String,
+ #[serde(default)]
pub properties: Vec<NotionPropertyConfig>,
}
diff --git a/src/main.rs b/src/main.rs
index 6fd7f93..cca5b82 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -40,6 +40,7 @@ async fn process_and_save_file(
output_dir: Option<&str>,
progress_bar: &ProgressBar,
notion_client: Option<&NotionClient>,
+ notion_config: Option<&NotionConfig>,
) -> Result<(), NotedError> {
let path = Path::new(file_path);
let file_name = match path.file_name() {
@@ -88,9 +89,14 @@ async fn process_and_save_file(
"✔".green(),
format!("Markdown saved to '{}'", output_path.cyan()).green()
));
- if let Some(client) = notion_client {
+ if let (Some(client), Some(config)) = (notion_client, notion_config) {
match client
- .create_notion_page(file_name.to_str().unwrap(), "Testing", &markdown)
+ .create_notion_page(
+ file_name.to_str().unwrap(),
+ &config.title_property_name,
+ &config.properties,
+ &markdown,
+ )
.await
{
Ok(page) => {
@@ -319,6 +325,20 @@ async fn run() -> Result<(), NotedError> {
spinner.finish_and_clear();
match schema_result {
Ok(schema) => {
+ let title_property_name = schema
+ .properties
+ .values()
+ .find(|prop| {
+ matches!(prop.type_specific_config, PropertyType::Title(_))
+ })
+ .map(|prop| prop.name.clone())
+ .ok_or_else(|| {
+ NotedError::ApiError(format!(
+ "{}",
+ "Database has no title property".red()
+ ))
+ })?;
+
let properties: Vec<_> = schema
.properties
.into_iter()
@@ -464,6 +484,7 @@ async fn run() -> Result<(), NotedError> {
config.notion = Some(NotionConfig {
api_key,
database_id,
+ title_property_name,
properties: default_properties,
});
config.save()?;
@@ -606,17 +627,16 @@ async fn run() -> Result<(), NotedError> {
format!("Input path not found: {}", path),
)));
}
- let notion_client = if notion {
- if let Some(notion_config) = &config.notion {
- Some(NotionClient::new(
- notion_config.api_key.clone(),
- notion_config.database_id.clone(),
- ))
+ let (notion_client, notion_config) = if notion {
+ if let Some(config) = &config.notion {
+ let client =
+ NotionClient::new(config.api_key.clone(), config.database_id.clone());
+ (Some(client), Some(config))
} else {
return Err(NotedError::NotionNotConfigured);
}
} else {
- None
+ (None, None)
};
if input_path.is_dir() {
@@ -656,6 +676,7 @@ async fn run() -> Result<(), NotedError> {
output.as_deref(),
&progress_bar,
notion_client.as_ref(),
+ notion_config,
)
.await
{
@@ -685,6 +706,7 @@ async fn run() -> Result<(), NotedError> {
output.as_deref(),
&progress_bar,
notion_client.as_ref(),
+ notion_config,
)
.await
{