-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
98 lines (79 loc) · 2.02 KB
/
utils.go
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"github.com/dstotijn/go-notion"
)
type PageBuilder struct {
Title string
Date string
DateEnd string
DatabaseID string
}
func Tmpl(name, s string, builder interface{}) ([]byte, error) {
tmpl, err := template.New(name).Parse(s)
if err != nil {
return nil, fmt.Errorf("template %s parse: %w", name, err)
}
var raw bytes.Buffer
if err = tmpl.Execute(&raw, builder); err != nil {
return nil, fmt.Errorf("template %s execute: %w", name, err)
}
return raw.Bytes(), nil
}
type BlockBuilder struct {
Date string
Content string
PageID string
}
type AppendBlock struct {
Client *notion.Client
AppendToPageID string
Blocks []notion.Block
}
func NewAppendBlock(c *notion.Client, appendTo string) *AppendBlock {
return &AppendBlock{
Client: c,
AppendToPageID: appendTo,
}
}
// https://pkg.go.dev/github.com/dstotijn/go-notion#ParagraphBlock
// https://pkg.go.dev/github.com/dstotijn/go-notion#RichText
func (a *AppendBlock) AddParagraph(name, s string, builder interface{}) error {
if s == "" {
return fmt.Errorf("empty block text: %s", name)
}
rawBlock, err := Tmpl(name, s, builder)
if err != nil {
return err
}
block := ¬ion.ParagraphBlock{}
if err := json.Unmarshal(rawBlock, block); err != nil {
return fmt.Errorf("unmarshal block: %w", err)
}
a.Blocks = append(a.Blocks, block)
return nil
}
func (a *AppendBlock) AddBlocks(name, s string, builder interface{}) error {
if s == "" {
return fmt.Errorf("empty block text: %s", name)
}
rawBlocks, err := Tmpl(name, s, builder)
if err != nil {
return err
}
blocks := []notion.ParagraphBlock{}
if err := json.Unmarshal(rawBlocks, &blocks); err != nil {
return fmt.Errorf("unmarshal blocks: %w", err)
}
for _, b := range blocks {
a.Blocks = append(a.Blocks, b)
}
return nil
}
func (a *AppendBlock) Do(ctx context.Context) (notion.BlockChildrenResponse, error) {
return a.Client.AppendBlockChildren(ctx, a.AppendToPageID, a.Blocks)
}