follow.go82 lines, 2.2 KB
| 1 | package users |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | |
| 7 | "github.com/fiston-user/murmur/internal/platform/httpx" |
| 8 | "github.com/jackc/pgx/v5" |
| 9 | ) |
| 10 | |
| 11 | // target finds the user named in the path, or answers 404. |
| 12 | func (h *Handler) target(w http.ResponseWriter, r *http.Request) (int64, bool) { |
| 13 | var id int64 |
| 14 | err := h.db.QueryRow(r.Context(), |
| 15 | `select id from users where handle = $1`, r.PathValue("handle")).Scan(&id) |
| 16 | if errors.Is(err, pgx.ErrNoRows) { |
| 17 | httpx.Error(w, http.StatusNotFound, "no such user") |
| 18 | return 0, false |
| 19 | } |
| 20 | if err != nil { |
| 21 | httpx.ServerError(w, r, err) |
| 22 | return 0, false |
| 23 | } |
| 24 | return id, true |
| 25 | } |
| 26 | |
| 27 | // Follow makes the caller follow the user in the path. Doing it twice is fine. |
| 28 | func (h *Handler) Follow(w http.ResponseWriter, r *http.Request) { |
| 29 | followee, ok := h.target(w, r) |
| 30 | if !ok { |
| 31 | return |
| 32 | } |
| 33 | if followee == ID(r.Context()) { |
| 34 | httpx.Error(w, http.StatusBadRequest, "you can't follow yourself") |
| 35 | return |
| 36 | } |
| 37 | _, err := h.db.Exec(r.Context(), ` |
| 38 | with added as ( |
| 39 | insert into follows (follower_id, followee_id) values ($1, $2) |
| 40 | on conflict do nothing |
| 41 | returning followee_id |
| 42 | ) |
| 43 | update users set followers_count = followers_count + 1 |
| 44 | where id in (select followee_id from added)`, |
| 45 | ID(r.Context()), followee) |
| 46 | if err != nil { |
| 47 | httpx.ServerError(w, r, err) |
| 48 | return |
| 49 | } |
| 50 | // Who they follow just changed, so their timeline is out of date. |
| 51 | if err := h.tl.Drop(r.Context(), ID(r.Context())); err != nil { |
| 52 | httpx.ServerError(w, r, err) |
| 53 | return |
| 54 | } |
| 55 | w.WriteHeader(http.StatusNoContent) |
| 56 | } |
| 57 | |
| 58 | // Unfollow undoes a follow. Unfollowing someone you don't follow is fine too. |
| 59 | func (h *Handler) Unfollow(w http.ResponseWriter, r *http.Request) { |
| 60 | followee, ok := h.target(w, r) |
| 61 | if !ok { |
| 62 | return |
| 63 | } |
| 64 | _, err := h.db.Exec(r.Context(), ` |
| 65 | with removed as ( |
| 66 | delete from follows where follower_id = $1 and followee_id = $2 |
| 67 | returning followee_id |
| 68 | ) |
| 69 | update users set followers_count = followers_count - 1 |
| 70 | where id in (select followee_id from removed)`, |
| 71 | ID(r.Context()), followee) |
| 72 | if err != nil { |
| 73 | httpx.ServerError(w, r, err) |
| 74 | return |
| 75 | } |
| 76 | // Who they follow just changed, so their timeline is out of date. |
| 77 | if err := h.tl.Drop(r.Context(), ID(r.Context())); err != nil { |
| 78 | httpx.ServerError(w, r, err) |
| 79 | return |
| 80 | } |
| 81 | w.WriteHeader(http.StatusNoContent) |
| 82 | } |