Skip to content

Add methods for modfifing pages and blocks #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 148 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ use crate::models::error::ErrorResponse;
use crate::models::search::{DatabaseQuery, SearchRequest};
use crate::models::{Database, ListResponse, Object, Page};
use ids::{AsIdentifier, PageId};
use models::block::Block;
use models::PageCreateRequest;
use models::block::{Block, CreateBlock};
use models::paging::PagingCursor;
use models::{PageCreateRequest, PageUpdateRequest, UpdateBlockChildrenRequest};
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{header, Client, ClientBuilder, RequestBuilder};
use tracing::Instrument;
Expand Down Expand Up @@ -199,6 +200,33 @@ impl NotionApi {
}
}

/// Updates a page and return the updated page
pub async fn update_page<P, T>(
&self,
page_id: P,
page: T,
) -> Result<Page, Error>
where
P: AsIdentifier<PageId>,
T: Into<PageUpdateRequest>,
{
let result = self
.make_json_request(
self.client
.patch(&format!(
"https://api.notion.com/v1/pages/{page_id}",
page_id = page_id.as_id()
))
.json(&page.into()),
)
.await?;

match result {
Object::Page { page } => Ok(page),
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Query a database and return the matching pages.
pub async fn query_database<D, T>(
&self,
Expand All @@ -225,6 +253,25 @@ impl NotionApi {
}
}

/// Get a block by [BlockId].
pub async fn get_block<T: AsIdentifier<BlockId>>(
&self,
page_id: T,
) -> Result<Block, Error> {
let result = self
.make_json_request(self.client.get(format!(
"https://api.notion.com/v1/blocks/{}",
page_id.as_id()
)))
.await?;

match result {
Object::Block { block } => Ok(block),
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Get block children a block by [BlockId].
pub async fn get_block_children<T: AsIdentifier<BlockId>>(
&self,
block_id: T,
Expand All @@ -241,4 +288,103 @@ impl NotionApi {
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Get block children a block by [BlockId].
pub async fn get_block_children_with_cursor<T: AsIdentifier<BlockId>>(
&self,
block_id: T,
cursor: PagingCursor,
) -> Result<ListResponse<Block>, Error> {
let result = self
.make_json_request(
self.client
.get(&format!(
"https://api.notion.com/v1/blocks/{block_id}/children",
block_id = block_id.as_id()
))
.query(&[("start_cursor", cursor.0)]),
)
.await?;

match result {
Object::List { list } => Ok(list.expect_blocks()?),
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Append block children under a block by [BlockId].
pub async fn append_block_children<P, T>(
&self,
block_id: P,
request: T,
) -> Result<ListResponse<Block>, Error>
where
P: AsIdentifier<BlockId>,
T: Into<UpdateBlockChildrenRequest>,
{
let result = self
.make_json_request(
self.client
.patch(&format!(
"https://api.notion.com/v1/blocks/{block_id}/children",
block_id = block_id.as_id()
))
.json(&request.into()),
)
.await?;

match result {
Object::List { list } => Ok(list.expect_blocks()?),
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Delete a block by [BlockId].
pub async fn delete_block<T: AsIdentifier<BlockId>>(
&self,
block_id: T,
) -> Result<Block, Error> {
let result = self
.make_json_request(self.client.delete(&format!(
"https://api.notion.com/v1/blocks/{block_id}",
block_id = block_id.as_id()
)))
.await?;

match result {
Object::Block { block } => Ok(block),
response => Err(Error::UnexpectedResponse { response }),
}
}

/// Update a block by [BlockId].
pub async fn update_block<P, T>(
&self,
block_id: P,
block: T,
) -> Result<Block, Error>
where
P: AsIdentifier<BlockId>,
T: Into<CreateBlock>,
{
// using CreateBlock is not perfect
// technically speaking you can update text on a todo block and not touch checked by not settings it
// but I don't want to create a new type for this
// or make checked optional in CreateBlock
let result = self
.make_json_request(
self.client
.patch(&format!(
"https://api.notion.com/v1/blocks/{block_id}",
block_id = block_id.as_id()
))
.json(&block.into()),
)
.await?;

match result {
Object::Block { block } => Ok(block),
response => Err(Error::UnexpectedResponse { response }),
}
}
}
18 changes: 16 additions & 2 deletions src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::ids::{AsIdentifier, DatabaseId, PageId};
use crate::models::block::{Block, CreateBlock};
use crate::models::block::{Block, CreateBlock, FileOrEmojiObject};
use crate::models::error::ErrorResponse;
use crate::models::paging::PagingCursor;
use crate::models::users::User;
Expand Down Expand Up @@ -182,14 +182,28 @@ impl Properties {
}
}

#[derive(Serialize, Debug, Eq, PartialEq)]
#[derive(Serialize, Debug, Eq, PartialEq, Clone)]
pub struct PageCreateRequest {
pub parent: Parent,
pub properties: Properties,
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<CreateBlock>>,
}

#[derive(Serialize, Debug, Eq, PartialEq, Clone)]
pub struct UpdateBlockChildrenRequest {
pub children: Vec<CreateBlock>,
}

#[derive(Serialize, Debug, Eq, PartialEq)]
pub struct PageUpdateRequest {
pub properties: Properties,
#[serde(skip_serializing_if = "Option::is_none")]
pub archived: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<FileOrEmojiObject>,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct Page {
pub id: PageId,
Expand Down
2 changes: 1 addition & 1 deletion src/models/paging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
#[serde(transparent)]
pub struct PagingCursor(String);
pub struct PagingCursor(pub(crate) String);

#[derive(Serialize, Debug, Eq, PartialEq, Default, Clone)]
pub struct Paging {
Expand Down
19 changes: 17 additions & 2 deletions src/models/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub struct Filter {
value: FilterValue,
}

#[derive(Serialize, Debug, Eq, PartialEq, Default)]
#[derive(Serialize, Debug, Eq, PartialEq, Default, Clone)]
pub struct SearchRequest {
#[serde(skip_serializing_if = "Option::is_none")]
query: Option<String>,
Expand All @@ -56,6 +56,21 @@ pub struct SearchRequest {
paging: Option<Paging>,
}

impl Pageable for SearchRequest {
fn start_from(
self,
starting_point: Option<PagingCursor>,
) -> Self {
SearchRequest {
paging: Some(Paging {
start_cursor: starting_point,
page_size: self.paging.and_then(|p| p.page_size),
}),
..self
}
}
}

#[derive(Serialize, Debug, Eq, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum TextCondition {
Expand Down Expand Up @@ -318,7 +333,7 @@ impl Pageable for DatabaseQuery {
}
}

#[derive(Debug, Eq, PartialEq)]
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum NotionSearch {
/// When supplied, limits which pages are returned by comparing the query to the page title.
Query(String),
Expand Down
13 changes: 10 additions & 3 deletions src/models/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,25 @@ pub enum TextColor {

/// Rich text annotations
/// See <https://developers.notion.com/reference/rich-text#annotations>
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Default)]
pub struct Annotations {
#[serde(skip_serializing_if = "Option::is_none")]
pub bold: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub color: Option<TextColor>,
#[serde(skip_serializing_if = "Option::is_none")]
pub italic: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub strikethrough: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub underline: Option<bool>,
}

/// Properties common on all rich text objects
/// See <https://developers.notion.com/reference/rich-text#all-rich-text>
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Default)]
pub struct RichTextCommon {
pub plain_text: String,
#[serde(skip_serializing_if = "Option::is_none")]
Expand All @@ -55,9 +61,10 @@ pub struct Link {
pub url: String,
}

#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Default)]
pub struct Text {
pub content: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub link: Option<Link>,
}

Expand Down
2 changes: 2 additions & 0 deletions src/models/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct UserCommon {
pub id: UserId,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar_url: Option<String>,
}

Expand Down