-
Notifications
You must be signed in to change notification settings - Fork 85
/
record.go
104 lines (99 loc) · 2.76 KB
/
record.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
99
100
101
102
103
104
package notionapi
import (
"encoding/json"
"fmt"
)
// Record represents a polymorphic record
type Record struct {
// fields returned by the server
Role string `json:"role"`
// polymorphic value of the record, which we decode into Block, Space etc.
Value json.RawMessage `json:"value"`
// fields calculated from Value based on type
ID string `json:"-"`
Table string `json:"-"`
Activity *Activity `json:"-"`
Block *Block `json:"-"`
Space *Space `json:"-"`
NotionUser *NotionUser `json:"-"`
UserRoot *UserRoot `json:"-"`
UserSettings *UserSettings `json:"-"`
Collection *Collection `json:"-"`
CollectionView *CollectionView `json:"-"`
Comment *Comment `json:"-"`
Discussion *Discussion `json:"-"`
// TODO: add more types
}
// table is not always present in Record returned by the server
// so must be provided based on what was asked
func parseRecord(table string, r *Record) error {
// it's ok if some records don't return a value
if len(r.Value) == 0 {
return nil
}
if r.Table == "" {
r.Table = table
} else {
// TODO: probably never happens
panicIf(r.Table != table)
}
// set Block/Space etc. based on TableView type
var pRawJSON *map[string]interface{}
var obj interface{}
switch table {
case TableActivity:
r.Activity = &Activity{}
obj = r.Activity
pRawJSON = &r.Activity.RawJSON
case TableBlock:
r.Block = &Block{}
obj = r.Block
pRawJSON = &r.Block.RawJSON
case TableNotionUser:
r.NotionUser = &NotionUser{}
obj = r.NotionUser
pRawJSON = &r.NotionUser.RawJSON
case TableUserRoot:
r.UserRoot = &UserRoot{}
obj = r.UserRoot
pRawJSON = &r.UserRoot.RawJSON
case TableUserSettings:
r.UserSettings = &UserSettings{}
obj = r.UserSettings
pRawJSON = &r.UserSettings.RawJSON
case TableSpace:
r.Space = &Space{}
obj = r.Space
pRawJSON = &r.Space.RawJSON
case TableCollection:
r.Collection = &Collection{}
obj = r.Collection
pRawJSON = &r.Collection.RawJSON
case TableCollectionView:
r.CollectionView = &CollectionView{}
obj = r.CollectionView
pRawJSON = &r.CollectionView.RawJSON
case TableDiscussion:
r.Discussion = &Discussion{}
obj = r.Discussion
pRawJSON = &r.Discussion.RawJSON
case TableComment:
r.Comment = &Comment{}
obj = r.Comment
pRawJSON = &r.Comment.RawJSON
}
if obj == nil {
return fmt.Errorf("unsupported table '%s'", r.Table)
}
if err := jsonit.Unmarshal(r.Value, pRawJSON); err != nil {
return err
}
id := (*pRawJSON)["id"]
if id != nil {
r.ID = id.(string)
}
if err := jsonit.Unmarshal(r.Value, &obj); err != nil {
return err
}
return nil
}