1
0
mirror of https://github.com/dstotijn/go-notion.git synced 2024-11-24 08:42:26 +02:00

Add "Retrieve a page property item" endpoint

This commit is contained in:
David Stotijn 2021-12-22 14:04:22 +01:00
parent 4c24b26ca4
commit 664a94d62b
3 changed files with 317 additions and 0 deletions

View File

@ -336,6 +336,43 @@ func (c *Client) FindBlockChildrenByID(ctx context.Context, blockID string, quer
return result, nil
}
// FindPagePropertyByID returns a page property.
// See: https://developers.notion.com/reference/retrieve-a-page-property
func (c *Client) FindPagePropertyByID(ctx context.Context, pageID, propID string, query *PaginationQuery) (result PagePropResponse, err error) {
req, err := c.newRequest(ctx, http.MethodGet, fmt.Sprintf("/pages/%v/properties/%v", pageID, propID), nil)
if err != nil {
return PagePropResponse{}, fmt.Errorf("notion: invalid request: %w", err)
}
if query != nil {
q := url.Values{}
if query.StartCursor != "" {
q.Set("start_cursor", query.StartCursor)
}
if query.PageSize != 0 {
q.Set("page_size", strconv.Itoa(query.PageSize))
}
req.URL.RawQuery = q.Encode()
}
res, err := c.httpClient.Do(req)
if err != nil {
return PagePropResponse{}, fmt.Errorf("notion: failed to make HTTP request: %w", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return PagePropResponse{}, fmt.Errorf("notion: failed to find page property: %w", parseErrorResponse(res))
}
err = json.NewDecoder(res.Body).Decode(&result)
if err != nil {
return PagePropResponse{}, fmt.Errorf("notion: failed to parse HTTP response: %w", err)
}
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) (result BlockChildrenResponse, err error) {

View File

@ -2602,6 +2602,247 @@ func TestUpdatePageProps(t *testing.T) {
}
}
func TestFindPagePropertyByID(t *testing.T) {
t.Parallel()
tests := []struct {
name string
query *notion.PaginationQuery
respBody func(r *http.Request) io.Reader
respStatusCode int
expQueryParams url.Values
expResponse notion.PagePropResponse
expError error
}{
{
name: "paginated property item, with query, successful response",
query: &notion.PaginationQuery{
StartCursor: "7c6b1c95-de50-45ca-94e6-af1d9fd295ab",
PageSize: 42,
},
respBody: func(_ *http.Request) io.Reader {
return strings.NewReader(
`{
"object": "list",
"results": [
{
"object": "property_item",
"type": "rich_text",
"rich_text": {
"type": "text",
"text": {
"content": "Foobar",
"link": null
},
"annotations": {
"bold": false,
"italic": false,
"strikethrough": false,
"underline": false,
"code": false,
"color": "default"
},
"plain_text": "Foobar",
"href": null
}
}
],
"next_cursor": "A^hd",
"has_more": true
}`,
)
},
respStatusCode: http.StatusOK,
expQueryParams: url.Values{
"start_cursor": []string{"7c6b1c95-de50-45ca-94e6-af1d9fd295ab"},
"page_size": []string{"42"},
},
expResponse: notion.PagePropResponse{
Results: []notion.PagePropItem{
{
Type: notion.DBPropTypeRichText,
RichText: notion.RichText{
Type: notion.RichTextTypeText,
Text: &notion.Text{
Content: "Foobar",
},
PlainText: "Foobar",
Annotations: &notion.Annotations{
Color: notion.ColorDefault,
},
},
},
},
HasMore: true,
NextCursor: "A^hd",
},
expError: nil,
},
{
name: "paginated property item, successful response",
query: nil,
respBody: func(_ *http.Request) io.Reader {
return strings.NewReader(
`{
"object": "list",
"results": [],
"next_cursor": null,
"has_more": false
}`,
)
},
respStatusCode: http.StatusOK,
expQueryParams: nil,
expResponse: notion.PagePropResponse{
Results: []notion.PagePropItem{},
HasMore: false,
NextCursor: "",
},
expError: nil,
},
{
name: "simple property item, successful response",
query: nil,
respBody: func(_ *http.Request) io.Reader {
return strings.NewReader(
`{
"object": "property_item",
"type": "number",
"number": 42
}`,
)
},
respStatusCode: http.StatusOK,
expQueryParams: nil,
expResponse: notion.PagePropResponse{
PagePropItem: notion.PagePropItem{
Type: notion.DBPropTypeNumber,
Number: 42,
},
},
expError: nil,
},
{
name: "rollup property item with aggregation, successful response",
query: nil,
respBody: func(_ *http.Request) io.Reader {
return strings.NewReader(
`{
"object": "list",
"results": [
{
"object": "property_item",
"type": "relation",
"relation": {
"id": "de5d73e8-3748-40fa-9102-f1290fe2444b"
}
},
{
"object": "property_item",
"type": "relation",
"relation": {
"id": "164325b0-4c9e-416b-ba9c-037b4c9acdfd"
}
},
{
"object": "property_item",
"type": "relation",
"relation": {
"id": "456baa98-3239-4c1f-b0ea-bdae945aaf33"
}
}
],
"type": "rollup"
"rollup": {
"type": "date",
"date": {
"start": "2021-10-07T14:42:00.000+00:00",
"end": null
},
"function": "latest_date"
},
"has_more": false,
}`,
)
},
respStatusCode: http.StatusOK,
expQueryParams: nil,
expResponse: notion.PagePropResponse{
PagePropItem: notion.PagePropItem{
Type: notion.DBPropTypeNumber,
Number: 42,
},
},
expError: nil,
},
{
name: "error response",
respBody: func(_ *http.Request) io.Reader {
return strings.NewReader(
`{
"object": "error",
"status": 400,
"code": "validation_error",
"message": "foobar"
}`,
)
},
respStatusCode: http.StatusBadRequest,
expResponse: notion.PagePropResponse{},
expError: errors.New("notion: failed to find page property: foobar (code: validation_error, status: 400)"),
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
httpClient := &http.Client{
Transport: &mockRoundtripper{fn: func(r *http.Request) (*http.Response, error) {
q := r.URL.Query()
if len(tt.expQueryParams) == 0 && len(q) != 0 {
t.Errorf("unexpected query params: %+v", q)
}
if len(tt.expQueryParams) != 0 && len(q) == 0 {
t.Errorf("query params not equal (expected %+v, got: nil)", tt.expQueryParams)
}
if len(tt.expQueryParams) != 0 && len(q) != 0 {
if diff := cmp.Diff(tt.expQueryParams, q); diff != "" {
t.Errorf("query params not equal (-exp, +got):\n%v", diff)
}
}
return &http.Response{
StatusCode: tt.respStatusCode,
Status: http.StatusText(tt.respStatusCode),
Body: ioutil.NopCloser(tt.respBody(r)),
}, nil
}},
}
client := notion.NewClient("secret-api-key", notion.WithHTTPClient(httpClient))
resp, err := client.FindPagePropertyByID(context.Background(), "page-id", "prop-id", tt.query)
if tt.expError == nil && err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tt.expError != nil && err == nil {
t.Fatalf("error not equal (expected: %v, got: nil)", tt.expError)
}
if tt.expError != nil && err != nil && tt.expError.Error() != err.Error() {
t.Fatalf("error not equal (expected: %v, got: %v)", tt.expError, err)
}
if diff := cmp.Diff(tt.expResponse, resp); diff != "" {
t.Fatalf("response not equal (-exp, +got):\n%v", diff)
}
})
}
}
func TestFindBlockChildrenById(t *testing.T) {
t.Parallel()

39
page.go
View File

@ -87,6 +87,45 @@ type UpdatePageParams struct {
Cover *Cover
}
// PagePropItem is used for a *single* property object value, e.g. for a `rich_text`
// property, a single value of an array of rich text elements.
// This type is used when fetching single properties.
type PagePropItem struct {
Type DatabasePropertyType `json:"type"`
Title RichText `json:"title"`
RichText RichText `json:"rich_text"`
Number float64 `json:"number"`
Select SelectOptions `json:"select"`
MultiSelect SelectOptions `json:"multi_select"`
Date Date `json:"date"`
Formula FormulaResult `json:"formula"`
Relation Relation `json:"relation"`
Rollup RollupResult `json:"rollup"`
People User `json:"people"`
Files File `json:"files"`
Checkbox bool `json:"checkbox"`
URL string `json:"url"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
CreatedTime time.Time `json:"created_time"`
CreatedBy User `json:"created_by"`
LastEditedTime time.Time `json:"last_edited_time"`
LastEditedBy User `json:"last_edited_by"`
}
// PagePropResponse contains a single database page property item or a list
// of items. For rollup props with an aggregation, both a `results` array and a
// `rollup` field is included.
// See: https://developers.notion.com/reference/retrieve-a-page-property#rollup-properties
type PagePropResponse struct {
PagePropItem
Results []PagePropItem `json:"results"`
HasMore bool `json:"has_more"`
NextCursor string `json:"next_cursor"`
}
// Value returns the underlying database page property value, based on its `type` field.
// When type is unknown/unmapped or doesn't have a value, `nil` is returned.
func (prop DatabasePageProperty) Value() interface{} {