The first public release of Fabled Minstrel #158

Merged
bvandeusen merged 256 commits from dev into main 2026-12-03 21:41:58 -05:00
4 changed files with 87 additions and 20 deletions
Showing only changes of commit 698ff23105 - Show all commits
+13 -4
View File
@@ -50,10 +50,18 @@ func (h *handlers) handleLikeTrack(w http.ResponseWriter, r *http.Request) {
}
// The like is on the song: every copy it reached changes on
// the client too.
for _, t := range eventbus.LedBy(id, liked) {
changed := eventbus.LedBy(id, liked)
for _, t := range changed {
h.publishLikeEvent(user.ID, t, "track", true)
}
w.WriteHeader(http.StatusNoContent)
writeJSON(w, http.StatusOK, trackLikeView{TrackIDs: uuidsToStrings(changed)})
}
// trackLikeView answers a track like or unlike: the copies of the song it
// changed, the one asked for first, so the client can mark them all at once
// rather than only the copy that was tapped.
type trackLikeView struct {
TrackIDs []string `json:"track_ids"`
}
func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) {
@@ -76,10 +84,11 @@ func (h *handlers) handleUnlikeTrack(w http.ResponseWriter, r *http.Request) {
h.logger.Error("api: soft-delete contextual_likes", "err", err)
// Don't fail the response — soft-delete is best-effort.
}
for _, t := range eventbus.LedBy(id, unliked) {
changed := eventbus.LedBy(id, unliked)
for _, t := range changed {
h.publishLikeEvent(user.ID, t, "track", false)
}
w.WriteHeader(http.StatusNoContent)
writeJSON(w, http.StatusOK, trackLikeView{TrackIDs: uuidsToStrings(changed)})
}
func (h *handlers) handleLikeAlbum(w http.ResponseWriter, r *http.Request) {
+32 -3
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"slices"
"testing"
"github.com/go-chi/chi/v5"
@@ -46,11 +47,11 @@ func TestLikeTrack_Idempotent(t *testing.T) {
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
if w.Code != http.StatusNoContent {
if w.Code != http.StatusOK {
t.Fatalf("first like: status = %d body=%s", w.Code, w.Body.String())
}
w = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID))
if w.Code != http.StatusNoContent {
if w.Code != http.StatusOK {
t.Errorf("second like (idempotent): status = %d", w.Code)
}
var count int
@@ -89,11 +90,39 @@ func TestUnlikeTrack_IdempotentEvenWhenAbsent(t *testing.T) {
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID))
if w.Code != http.StatusNoContent {
if w.Code != http.StatusOK {
t.Errorf("status = %d", w.Code)
}
}
// A like is on the song, so its answer names every copy it reached, and an
// unlike every copy it cleared, the tapped one first.
func TestLikeTrack_AnswersEveryCopyOfTheSong(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
user := seedUser(t, pool, "alice", "x", false)
artist := seedArtist(t, pool, "Copper Lanterns")
album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969)
best := seedAlbum(t, pool, artist.ID, "Best Of", 1975)
first := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
copied := seedTrack(t, pool, best.ID, artist.ID, "Something", 1, 183_000)
if _, err := pool.Exec(context.Background(), "UPDATE tracks SET song_id = $1 WHERE id = $2", first.ID, copied.ID); err != nil {
t.Fatal(err)
}
want := []string{uuidToString(copied.ID), uuidToString(first.ID)}
for _, method := range []string{http.MethodPost, http.MethodDelete} {
w := callLike(h, user, method, "/api/likes/tracks/"+uuidToString(copied.ID))
var got trackLikeView
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("%s: decode %q: %v", method, w.Body.String(), err)
}
if !slices.Equal(got.TrackIDs, want) {
t.Errorf("%s: track_ids = %v, want %v", method, got.TrackIDs, want)
}
}
}
func TestListLikedTracks_PaginatedAndSortedDescByLikedAt(t *testing.T) {
h, pool := testHandlers(t)
truncateLibrary(t, pool)
+12
View File
@@ -85,6 +85,18 @@ describe('likes mutations', () => {
expect(cached?.track_ids).toContain('t1');
});
test('a like marks every copy of the song the server names, and an unlike clears them', async () => {
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ track_ids: ['t2', 't2-best-of'] });
await likeEntity(client, 'track', 't2');
let cached = client.getQueryData(qk.likedIds()) as { track_ids: string[] } | undefined;
expect(cached?.track_ids).toEqual(['t1', 't2', 't2-best-of']);
(api.del as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ track_ids: ['t2-best-of', 't2'] });
await unlikeEntity(client, 'track', 't2-best-of');
cached = client.getQueryData(qk.likedIds()) as { track_ids: string[] } | undefined;
expect(cached?.track_ids).toEqual(['t1']);
});
test('a failed unlike puts back only its own like', async () => {
(api.del as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('boom'));
await expect(unlikeEntity(client, 'track', 't1')).rejects.toThrow('boom');
+30 -13
View File
@@ -82,35 +82,52 @@ function wasLiked(client: QueryClient, kind: EntityKind, id: string): boolean |
return client.getQueryData<LikedIdsResponse>(qk.likedIds())?.[SET_KEY_BY_KIND[kind]].includes(id);
}
// likeEntity shows the like straight away, then tells the server. If the
// server refuses, only this id goes back to how it was: a like or unlike made
// while the request was out keeps its own state. unlikeEntity is the same.
// A track like or unlike answers with every copy of the song it changed (the
// same song on another album or a compilation); album and artist likes
// answer nothing.
type TrackLikeResponse = { track_ids?: string[] } | null;
// likeEntity shows the like straight away, then tells the server, and marks
// the song's other copies once the server names them. If the server refuses,
// only this id goes back to how it was: a like or unlike made while the
// request was out keeps its own state. unlikeEntity is the same.
export async function likeEntity(
client: QueryClient,
kind: EntityKind,
id: string
): Promise<void> {
const before = wasLiked(client, kind, id);
setLiked(client, kind, id, true);
try {
await api.post(`/api/likes/${PATH_BY_KIND[kind]}/${id}`, undefined);
} catch (err) {
if (before !== undefined) setLiked(client, kind, id, before);
throw err;
}
await changeLike(client, kind, id, true, () =>
api.post<TrackLikeResponse>(`/api/likes/${PATH_BY_KIND[kind]}/${id}`, undefined)
);
}
export async function unlikeEntity(
client: QueryClient,
kind: EntityKind,
id: string
): Promise<void> {
await changeLike(client, kind, id, false, () =>
api.del<TrackLikeResponse>(`/api/likes/${PATH_BY_KIND[kind]}/${id}`)
);
}
async function changeLike(
client: QueryClient,
kind: EntityKind,
id: string,
liked: boolean,
send: () => Promise<TrackLikeResponse>
): Promise<void> {
const before = wasLiked(client, kind, id);
setLiked(client, kind, id, false);
setLiked(client, kind, id, liked);
let res: TrackLikeResponse;
try {
await api.del(`/api/likes/${PATH_BY_KIND[kind]}/${id}`);
res = await send();
} catch (err) {
if (before !== undefined) setLiked(client, kind, id, before);
throw err;
}
for (const copy of res?.track_ids ?? []) {
if (copy !== id) setLiked(client, kind, copy, liked);
}
}