Files
ersatztv/web/src/api/playlists.test.ts
T
timothyandClaude Opus 4.8 ef2bd65c27
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 10s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 10s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 1m12s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 3m4s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 8m17s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 10m36s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(api): #286 — mount the whole /api surface at /api/v1
Version every /api route to /api/v1 (251 controller routes + ~24 Location
headers + the scanner callback URL + the Startup request-log literal),
uniform across the machine API, auth, scanner and scripted-build surfaces.

Add ApiVersionRewriteMiddleware: a legacy unversioned /api/* request is
rewritten (NOT redirected) to /api/v1/* in-pipeline — method, body, auth
headers and query survive — carrying RFC 8594 Deprecation/Sunset headers,
so curl / the future MCP server / bookmarks keep working. An already-
versioned path passes through; a future /api/v2 is never forced to v1.

Standardize the route convention (leading-slash absolute route per method,
no class-[Route] — except the two Scanner/Scripted controllers whose ~all
actions share a parametrized {id} prefix), enforced by ApiRouteVersioningTests
(^/api/v\d+/ over the whole Controllers.Api surface; browser-nav
/auth/oidc/login is out of scope).

Regenerate v1.json (160 paths, all /api/v1)/endpoint-index/v1.d.ts; sweep 945
SPA request literals + the test mocks (regex + positional URL parsers). /api/v1
is additive-only after freeze; the legacy-rewrite shim sunsets in ~2 releases
(owner decision) with removal tracked as a Phase-3 follow-up.

Docs: decisions.md 2026-07-13, api-conventions §1/§9, rest-api/spa-conventions/
blazor-route-parity/e2e-local/domain-model.

fixes #286
refs #197

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 00:30:20 +02:00

161 lines
6.4 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
addItemsToPlaylist,
createPlaylist,
createPlaylistGroup,
deletePlaylist,
deletePlaylistGroup,
getPlaylistById,
getPlaylistGroups,
getPlaylistItems,
getPlaylists,
messageFromPlaylistError,
previewPlaylist,
updatePlaylist,
updatePlaylistGroup,
type PlaylistItemRequest
} from './playlists';
import { ApiError } from './client';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
function lastCall(fetchMock: ReturnType<typeof vi.spyOn>) {
const call = fetchMock.mock.calls[fetchMock.mock.calls.length - 1];
return { init: call[1] as RequestInit | undefined, url: String(call[0]) };
}
const sampleItem: PlaylistItemRequest = {
collectionId: 7,
collectionType: 'Collection',
count: null,
includeInProgramGuide: true,
index: 0,
mediaItemId: null,
multiCollectionId: null,
playAll: true,
playbackOrder: 'Chronological',
smartCollectionId: null
};
describe('playlists api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getPlaylistGroups fetches all playlist groups', async () => {
const fetchMock = vi
.spyOn(window, 'fetch')
.mockResolvedValue(jsonResponse([{ id: 1, isSystem: false, name: 'Idents', playlistCount: 2 }]));
await expect(getPlaylistGroups()).resolves.toHaveLength(1);
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists/groups', expect.objectContaining({ method: 'GET' }));
});
it('createPlaylistGroup POSTs the name', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 5, isSystem: false, name: 'New', playlistCount: 0 }, 201));
await createPlaylistGroup({ name: 'New' });
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists/groups');
expect(init?.method).toBe('POST');
expect(JSON.parse(String(init?.body))).toEqual({ name: 'New' });
});
it('updatePlaylistGroup PUTs the renamed group', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 5, isSystem: false, name: 'Renamed', playlistCount: 0 }));
await updatePlaylistGroup(5, { name: 'Renamed' });
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists/groups/5');
expect(init?.method).toBe('PUT');
expect(JSON.parse(String(init?.body))).toEqual({ name: 'Renamed' });
});
it('deletePlaylistGroup DELETEs the group', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await deletePlaylistGroup(9);
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists/groups/9', expect.objectContaining({ method: 'DELETE' }));
});
it('getPlaylists filters by playlist group id', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
await getPlaylists(3);
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists?playlistGroupId=3', expect.objectContaining({ method: 'GET' }));
});
it('getPlaylistById fetches a single playlist', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, isSystem: false, name: 'Bumps', playlistGroupId: 3 }));
await expect(getPlaylistById(4)).resolves.toMatchObject({ id: 4 });
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists/4', expect.objectContaining({ method: 'GET' }));
});
it('getPlaylistItems fetches the items of a playlist', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
await getPlaylistItems(4);
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists/4/items', expect.objectContaining({ method: 'GET' }));
});
it('createPlaylist POSTs the group id and name', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 8, isSystem: false, name: 'Bumps', playlistGroupId: 3 }, 201));
await createPlaylist({ name: 'Bumps', playlistGroupId: 3 });
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists');
expect(init?.method).toBe('POST');
expect(JSON.parse(String(init?.body))).toEqual({ name: 'Bumps', playlistGroupId: 3 });
});
it('updatePlaylist PUTs the name and item list', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
await updatePlaylist(4, { items: [sampleItem], name: 'Bumps' });
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists/4');
expect(init?.method).toBe('PUT');
expect(JSON.parse(String(init?.body))).toEqual({ items: [sampleItem], name: 'Bumps' });
});
it('deletePlaylist DELETEs the playlist', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await deletePlaylist(4);
expect(fetchMock).toHaveBeenCalledWith('/api/v1/playlists/4', expect.objectContaining({ method: 'DELETE' }));
});
it('previewPlaylist POSTs the draft to the preview endpoint', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse([]));
await previewPlaylist({ items: [sampleItem], name: 'Draft' });
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists/preview');
expect(init?.method).toBe('POST');
expect(JSON.parse(String(init?.body))).toEqual({ items: [sampleItem], name: 'Draft' });
});
it('addItemsToPlaylist POSTs the bucketed ids to the items endpoint', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
const body = {
artistIds: [],
episodeIds: [],
imageIds: [],
movieIds: [12],
musicVideoIds: [],
otherVideoIds: [],
remoteStreamIds: [],
seasonIds: [],
showIds: [3],
songIds: []
};
await addItemsToPlaylist(6, body);
const { init, url } = lastCall(fetchMock);
expect(url).toBe('/api/v1/playlists/6/items');
expect(init?.method).toBe('POST');
expect(JSON.parse(String(init?.body))).toEqual(body);
});
it('messageFromPlaylistError prefers ApiError detail', () => {
expect(messageFromPlaylistError(new ApiError(422, { detail: 'Name is required' }))).toBe('Name is required');
expect(messageFromPlaylistError('nope', 'fallback')).toBe('fallback');
});
});