feed.go83 lines, 2.2 KB
| 1 | // Package feed is the home feed: the posts of the people you follow. |
| 2 | package feed |
| 3 | |
| 4 | import ( |
| 5 | "math" |
| 6 | "net/http" |
| 7 | "strconv" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/murmur/internal/platform/httpx" |
| 11 | "github.com/fiston-user/murmur/internal/platform/replica" |
| 12 | "github.com/fiston-user/murmur/internal/timeline" |
| 13 | "github.com/fiston-user/murmur/internal/users" |
| 14 | "github.com/jackc/pgx/v5" |
| 15 | ) |
| 16 | |
| 17 | // Post is one post in a feed, with its author's handle. |
| 18 | type Post struct { |
| 19 | ID int64 `json:"id"` |
| 20 | Handle string `json:"handle"` |
| 21 | Body string `json:"body"` |
| 22 | CreatedAt time.Time `json:"created_at"` |
| 23 | Likes int `json:"likes"` |
| 24 | Liked bool `json:"liked"` // by the caller |
| 25 | } |
| 26 | |
| 27 | // Page is one page of a feed. NextCursor is null on the last page. |
| 28 | type Page struct { |
| 29 | NextCursor *int64 `json:"next_cursor"` |
| 30 | Posts []Post `json:"posts"` |
| 31 | } |
| 32 | |
| 33 | type Handler struct { |
| 34 | reads *replica.Reads |
| 35 | tl *timeline.Store |
| 36 | } |
| 37 | |
| 38 | func New(reads *replica.Reads, tl *timeline.Store) *Handler { |
| 39 | return &Handler{reads: reads, tl: tl} |
| 40 | } |
| 41 | |
| 42 | // List returns a page of the caller's home feed, newest first. |
| 43 | func (h *Handler) List(w http.ResponseWriter, r *http.Request) { |
| 44 | q := r.URL.Query() |
| 45 | limit, _ := strconv.Atoi(q.Get("limit")) |
| 46 | if limit < 1 { |
| 47 | limit = 20 |
| 48 | } |
| 49 | limit = min(limit, 100) |
| 50 | cursor := int64(math.MaxInt64) |
| 51 | if s := q.Get("cursor"); s != "" { |
| 52 | id, err := strconv.ParseInt(s, 10, 64) |
| 53 | if err != nil || id < 1 { |
| 54 | httpx.Error(w, http.StatusBadRequest, "cursor must be a post id") |
| 55 | return |
| 56 | } |
| 57 | cursor = id |
| 58 | } |
| 59 | db := h.reads.For(r.Context(), users.ID(r.Context())) |
| 60 | ids, err := h.tl.Page(r.Context(), db, users.ID(r.Context()), cursor, limit+1) |
| 61 | if err != nil { |
| 62 | httpx.ServerError(w, r, err) |
| 63 | return |
| 64 | } |
| 65 | rows, _ := db.Query(r.Context(), ` |
| 66 | select p.id, u.handle, p.body, p.created_at, p.likes_count, |
| 67 | exists (select 1 from likes where post_id = p.id and user_id = $2) |
| 68 | from posts p |
| 69 | join users u on u.id = p.user_id |
| 70 | where p.id = any($1) |
| 71 | order by p.id desc`, ids, users.ID(r.Context())) |
| 72 | posts, err := pgx.CollectRows(rows, pgx.RowToStructByPos[Post]) |
| 73 | if err != nil { |
| 74 | httpx.ServerError(w, r, err) |
| 75 | return |
| 76 | } |
| 77 | page := Page{Posts: posts} |
| 78 | if len(posts) > limit { |
| 79 | page.Posts = posts[:limit] |
| 80 | page.NextCursor = &posts[limit-1].ID |
| 81 | } |
| 82 | httpx.JSON(w, http.StatusOK, page) |
| 83 | } |