// Person 定義了 JSON 資料的結構體
type Person struct {
Name string `json:"name"`
Title string `json:"title"`
Address string `json:"address"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
}
// DatabaseEntry 定義了 Notion 資料庫條目的結構體。
type NotionDB struct {
DatabaseID string
Token string
}
// QueryDatabase 根據提供的屬性和值查詢 Notion 資料庫。
func (n *NotionDB) QueryDatabase(UId, property, value string) ([]Person, error) {
client := notionapi.NewClient(notionapi.Token(n.Token))
// Add UId to the filter conditions
// 建立查詢過濾條件
filter := ¬ionapi.DatabaseQueryRequest{
Filter: notionapi.AndCompoundFilter{
notionapi.PropertyFilter{
Property: property,
RichText: ¬ionapi.TextFilterCondition{
Equals: value,
},
},
notionapi.PropertyFilter{
Property: "UID",
RichText: ¬ionapi.TextFilterCondition{
Equals: UId,
},
},
},
}
// 調用 Notion API 來查詢資料庫
result, err := client.Database.Query(context.Background(), notionapi.DatabaseID(n.DatabaseID), filter)
if err != nil {
return nil, err
}
var entries []Person
for _, page := range result.Results {
entry := n.createEntryFromPage(&page)
entries = append(entries, entry)
}
return entries, nil
}
// AddPageToDatabase adds a new page with the provided field values to the specified Notion database.
func (n *NotionDB) AddPageToDatabase(Uid string, name string, title string, address string, email string, phoneNumber string) error {
client := notionapi.NewClient(notionapi.Token(n.Token))
// 建立 Properties 物件來設置頁面屬性
properties := notionapi.Properties{
"UID": notionapi.RichTextProperty{
RichText: []notionapi.RichText{
{
PlainText: name,
Text: ¬ionapi.Text{Content: Uid},
},
},
},
"Name": notionapi.TitleProperty{
Title: []notionapi.RichText{
{
PlainText: name,
Text: ¬ionapi.Text{Content: name},
},
},
},
// Address, Email, Phone Number....
}
// 創建一個新頁面的請求
pageRequest := ¬ionapi.PageCreateRequest{
Parent: notionapi.Parent{
DatabaseID: notionapi.DatabaseID(n.DatabaseID),
},
Properties: properties,
}
// 調用 Notion API 來創建新頁面
_, err := client.Page.Create(context.Background(), pageRequest)
if err != nil {
log.Println("Error creating page:", err)
return err
}
log.Println("Page added successfully:", Uid, name, title, address, email, phoneNumber)
return nil
}
"UID": notionapi.RichTextProperty{
RichText: []notionapi.RichText{
{
PlainText: name,
Text: ¬ionapi.Text{Content: Uid},
},
},
},
func TestAddNotionDB(t *testing.T) {
token := os.Getenv("NOTION_INTEGRATION_TOKEN")
pageid := os.Getenv("NOTION_DB_PAGEID")
// If not set token and pageid , skip this test
if token == "" || pageid == "" {
t.Skip("NOTION_INTEGRATION_TOKEN or NOTION_DB_PAGEID not set")
}
db := &NotionDB{
DatabaseID: pageid,
Token: token,
}
err := db.AddPageToDatabase("uid", "name", "title", "address", "[email protected]", "phone")
if err != nil {
t.Fatal(err)
}
}