forked from peterhellberg/hn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitems.go
70 lines (59 loc) · 1.6 KB
/
items.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
package hn
import (
"context"
"fmt"
"time"
)
// ItemsService communicates with the news
// related endpoints in the Hacker News API
type ItemsService interface {
Get(ctx context.Context, id int) (*Item, error)
}
// itemsService implements ItemsService.
type itemsService struct {
client *Client
}
// Item represents a item
type Item struct {
ID int `json:"id"`
Parent int `json:"parent"`
Kids []int `json:"kids"`
Descendants int `json:"descendants"`
Parts []int `json:"parts"`
Score int `json:"score"`
Timestamp int `json:"time"`
By string `json:"by"`
Type string `json:"type"`
Title string `json:"title"`
Text string `json:"text"`
URL string `json:"url"`
Dead bool `json:"dead"`
Deleted bool `json:"deleted"`
}
// Time return the time of the timestamp
func (i *Item) Time() time.Time {
return time.Unix(int64(i.Timestamp), 0)
}
// Item is a convenience method proxying Items.Get
func (c *Client) Item(ctx context.Context, id int) (*Item, error) {
return c.Items.Get(ctx, id)
}
// Get retrieves an item with the given id
func (s *itemsService) Get(ctx context.Context, id int) (*Item, error) {
req, err := s.client.NewRequest(ctx, s.getPath(id))
if err != nil {
return nil, err
}
var item Item
_, err = s.client.Do(req, &item)
if err != nil {
return nil, err
}
if item.Type == "story" && item.URL == "" {
item.URL = fmt.Sprintf("https://news.ycombinator.com/item?id=%v", id)
}
return &item, nil
}
func (s *itemsService) getPath(id int) string {
return fmt.Sprintf("item/%v.json", id)
}