From 205f94cc891ad153e4e70b347c5cc529df59d6a2 Mon Sep 17 00:00:00 2001 From: David Stotijn Date: Sat, 15 May 2021 20:16:04 +0200 Subject: [PATCH] Add "append block children" endpoint support --- README.md | 2 +- block.go | 2 +- client.go | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8bf678f..fb85a23 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Go client for the [Notion API](https://developers.notion.com/reference). ### Blocks - [x] [Retrieve block children](client.go) -- [ ] Append block children +- [x] [Append block children](client.go) ### Users diff --git a/block.go b/block.go index 2f9469e..c8e3a99 100644 --- a/block.go +++ b/block.go @@ -10,7 +10,7 @@ type Block struct { Type BlockType `json:"type"` CreatedTime *time.Time `json:"created_time,omitempty"` LastEditedTime *time.Time `json:"last_edited_time,omitempty"` - HasChildren bool `json:"has_children"` + HasChildren bool `json:"has_children,omitempty"` Paragraph *RichTextBlock `json:"paragraph,omitempty"` Heading1 *Heading `json:"heading_1,omitempty"` diff --git a/client.go b/client.go index f82b659..8fc47f3 100644 --- a/client.go +++ b/client.go @@ -261,3 +261,41 @@ func (c *Client) FindBlockChildrenByID(ctx context.Context, blockID string, quer return result, nil } + +// AppendBlockChildren appends child content (blocks) to an existing block. +// See: https://developers.notion.com/reference/patch-block-children +func (c *Client) AppendBlockChildren(ctx context.Context, blockID string, children []Block) (block Block, err error) { + type PostBody struct { + Children []Block `json:"children"` + } + + dto := PostBody{children} + body := &bytes.Buffer{} + + err = json.NewEncoder(body).Encode(dto) + if err != nil { + return Block{}, fmt.Errorf("notion: failed to encode body params to JSON: %w", err) + } + + req, err := c.newRequest(ctx, http.MethodPatch, fmt.Sprintf("/blocks/%v/children", blockID), body) + if err != nil { + return Block{}, fmt.Errorf("notion: invalid request: %w", err) + } + + res, err := c.httpClient.Do(req) + if err != nil { + return Block{}, fmt.Errorf("notion: failed to make HTTP request: %w", err) + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + return Block{}, fmt.Errorf("notion: failed to append block children: %w", parseErrorResponse(res)) + } + + err = json.NewDecoder(res.Body).Decode(&block) + if err != nil { + return Block{}, fmt.Errorf("notion: failed to parse HTTP response: %w", err) + } + + return block, nil +}