v3: api/ gets one layout rule and keeps to it, and whatever crosses the wire is defined once, in shared/ — api/model/interfaces.ts and src/model.ts declared the same 40 types by hand and had drifted: the error envelope, email required on one side and optional on the other, Invitee/InviteTreeEntry and LinkPreview/UrlPreviewResponse for one shape each. The validation limits, the role permissions, the chat length cap, the @mention pattern and the Bandcamp and YouTube player responses were copied too, behind "keep in sync" comments. shared/ now holds them once, one file per domain (api, category, chat, comment, dump, follow, mention, notification, permissions, player, playlist, search, user, validation, ws), and imports nothing from either half. The server sends Dates; the client reads Wire<T>, the same type with every Date an ISO string, and turns it back with src/utils/shared/deserialize.ts. APIErrorCode becomes a const object, since the frontend's erasableSyntaxOnly rejects an enum. The shared types showed two real gaps: the avatar upload and GET /api/users/me return the full self user and the frontend read them as public users, and a stored session may predate media tokens, so the client keeps it as its own Session type. The backend rule: each folder holds one kind of module, each file is named after its domain. routes/ parse and answer; services/ hold the logic and every SQL query (lib/auth.ts's token check moves to user-service); remote/ is the only place that fetches from other sites — the guarded fetch and the HTML scraping out of rich-content-service, public-address, the Bandcamp and YouTube resolvers, the link providers, the image proxy (fetch, checks and cache, out of routes/preview.ts) and the Twemoji glyphs (out of lib/site-icons.ts). model/ holds per table a row type, its guard and its mappers; validators/ the request guards; db/connection.ts the handle and transaction(), db/startup.ts the purges and default admin that db.ts ran on import, called at the same moment. Tests mirror the source one file per module, test/<layer>/<module>.test.ts, with shared/'s under shared/test/ (deno task test runs both); the test that covered the bandcamp and soundcloud providers together is two now, and the backend can() has its own, so 202 tests. deno lint src/ is clean too: window.* becomes globalThis.*, and test bodies and act() callbacks that never awaited lose their async. The README states the rule. No behaviour changes; the catalogues only move their source references.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-27 20:19:48 +00:00
parent e9f6a1f23e
commit d392be7cb8
269 changed files with 6712 additions and 7122 deletions

View File

@@ -6,25 +6,21 @@ import { dumpThumbnailUrl, dumpUrl } from "../utils/shared/urls.ts";
import { can } from "../utils/auth/permissions.ts";
import { AddToPlaylistModal } from "../components/playlist/AddToPlaylistModal.tsx";
import { API_URL, VALIDATION } from "../config/api.ts";
import { API_URL } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import type {
Comment,
Dump,
Playlist,
PublicUser,
RawComment,
RawDump,
RawPlaylist,
UpdateDumpRequest,
} from "../model.ts";
import type { Comment } from "../../shared/comment.ts";
import type { Dump, UpdateDumpRequest } from "../../shared/dump.ts";
import type { Playlist } from "../../shared/playlist.ts";
import type { PublicUser } from "../../shared/user.ts";
import type { Wire } from "../../shared/api.ts";
import {
deserializeComment,
deserializeDump,
deserializePlaylist,
deserializePublicUser,
parseAPIResponse,
} from "../model.ts";
} from "../utils/shared/deserialize.ts";
import { friendlyFetchError, parseAPIResponse } from "../utils/shared/api.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useCategories } from "../hooks/category/useCategories.ts";
@@ -43,7 +39,6 @@ import { PageError } from "../components/layout/PageError.tsx";
import { Markdown } from "../components/editor/Markdown.tsx";
import { CommentThread } from "../components/comment/CommentThread.tsx";
import { Tooltip } from "../components/shared/Tooltip.tsx";
import { friendlyFetchError } from "../utils/shared/api.ts";
type DumpState =
| { status: "loading" }
@@ -115,7 +110,7 @@ export function Dump() {
cache: "no-store",
signal: controller.signal,
});
const apiResponse = parseAPIResponse<RawDump>(await res.json());
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
if (!apiResponse.success) {
throw new Error(apiResponse.error.message);
}
@@ -159,7 +154,7 @@ export function Dump() {
.then((r) => r.json())
.then((body) => {
if (body.success) {
setComments((body.data as RawComment[]).map(deserializeComment));
setComments((body.data as Wire<Comment>[]).map(deserializeComment));
}
})
.catch(() => {});
@@ -178,7 +173,7 @@ export function Dump() {
.then((r) => r.json())
.then((body) => {
if (body.success) {
setRelatedDumps((body.data as RawDump[]).map(deserializeDump));
setRelatedDumps((body.data as Wire<Dump>[]).map(deserializeDump));
}
})
.catch(() => {});
@@ -196,7 +191,9 @@ export function Dump() {
.then((r) => r.json())
.then((body) => {
if (body.success) {
setCollections((body.data as RawPlaylist[]).map(deserializePlaylist));
setCollections(
(body.data as Wire<Playlist>[]).map(deserializePlaylist),
);
}
})
.catch(() => {});
@@ -321,7 +318,7 @@ export function Dump() {
{ title: trimmed } satisfies UpdateDumpRequest,
),
});
const apiResponse = parseAPIResponse<RawDump>(await res.json());
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
if (!apiResponse.success) {
setTitleError(apiResponse.error.message);
return;

View File

@@ -3,10 +3,17 @@ import { Link, useNavigate, useParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, VALIDATION } from "../config/api.ts";
import type { Dump, RawDump, UpdateDumpRequest } from "../model.ts";
import { deserializeDump, parseAPIResponse } from "../model.ts";
import { useRequiredAuth } from "../hooks/auth/useAuth.ts";
import { API_URL } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import type { Dump, UpdateDumpRequest } from "../../shared/dump.ts";
import type { Wire } from "../../shared/api.ts";
import { deserializeDump } from "../utils/shared/deserialize.ts";
import {
expectOk,
friendlyFetchError,
parseAPIResponse,
} from "../utils/shared/api.ts";
import { useAuth, useRequiredAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { formatBytes } from "../utils/shared/format.ts";
import {
@@ -17,13 +24,11 @@ import {
import { PageShell } from "../components/layout/PageShell.tsx";
import { PageError } from "../components/layout/PageError.tsx";
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
import { friendlyFetchError } from "../utils/shared/api.ts";
import { ConfirmModal } from "../components/shared/ConfirmModal.tsx";
import { RichContentCard } from "../components/dump/RichContentCard.tsx";
import { FilePreview } from "../components/dump/FilePreview.tsx";
import { ImagePicker } from "../components/shared/ImagePicker.tsx";
import { CategorySelect } from "../components/category/CategorySelect.tsx";
import { expectOk } from "../utils/shared/api.ts";
import { FileField } from "../components/form/FileField.tsx";
import { FormError } from "../components/form/FormError.tsx";
import { FormProvider } from "react-hook-form";
@@ -32,7 +37,6 @@ import { SubmitButton } from "../components/form/SubmitButton.tsx";
import { TextField } from "../components/form/TextField.tsx";
import { useApiForm } from "../hooks/form/useApiForm.ts";
import { VisibilityToggle } from "../components/form/SegmentedField.tsx";
import { useAuth } from "../hooks/auth/useAuth.ts";
type DumpEditState =
| { status: "loading" }
@@ -71,7 +75,7 @@ export function DumpEdit() {
cache: "no-store",
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
const apiResponse = parseAPIResponse<RawDump>(await res.json());
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
if (apiResponse.success) {
setState({
@@ -97,7 +101,7 @@ export function DumpEdit() {
`${API_URL}/api/dumps/${state.dump.id}/refresh-metadata`,
{ method: "POST" },
);
const apiResponse = parseAPIResponse<RawDump>(await res.json());
const apiResponse = parseAPIResponse<Wire<Dump>>(await res.json());
if (apiResponse.success) {
setState({ status: "loaded", dump: deserializeDump(apiResponse.data) });
} else {
@@ -115,7 +119,7 @@ export function DumpEdit() {
setThumbUploading(true);
setThumbError(null);
try {
const updated = await expectOk<RawDump>(
const updated = await expectOk<Wire<Dump>>(
await authFetch(
`${API_URL}/api/dumps/${state.dump.id}/thumbnail`,
init,
@@ -377,7 +381,7 @@ function DumpEditForm({
});
}
onSaved(deserializeDump(await expectOk<RawDump>(res)));
onSaved(deserializeDump(await expectOk<Wire<Dump>>(res)));
},
);

View File

@@ -20,13 +20,9 @@ import { useDefaultFeedTab } from "../hooks/feed/useDefaultFeedTab.ts";
import { API_URL, DEFAULT_PAGE_SIZE } from "../config/api.ts";
import {
deserializeDump,
type Dump,
hydrateDump,
type PaginatedData,
type RawDump,
} from "../model.ts";
import { deserializeDump, hydrateDump } from "../utils/shared/deserialize.ts";
import type { Dump } from "../../shared/dump.ts";
import type { PaginatedData, Wire } from "../../shared/api.ts";
import { friendlyFetchError } from "../utils/shared/api.ts";
import { useFeedCache } from "../hooks/feed/useFeedCache.ts";
@@ -154,7 +150,7 @@ export function Index({ categorySlug }: { categorySlug?: string }) {
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
const { items, hasMore } = body.data as PaginatedData<RawDump>;
const { items, hasMore } = body.data as PaginatedData<Wire<Dump>>;
setDumpsState({
status: "loaded",
dumps: items.map(deserializeDump),
@@ -200,7 +196,7 @@ export function Index({ categorySlug }: { categorySlug?: string }) {
})
.then((r) => r.json())
.then((body) => {
const { items } = body.data as PaginatedData<RawDump>;
const { items } = body.data as PaginatedData<Wire<Dump>>;
const fresh = items.map(deserializeDump);
setDumpsState((s) => {
if (s.status !== "loaded") return s;
@@ -230,7 +226,7 @@ export function Index({ categorySlug }: { categorySlug?: string }) {
})
.then((r) => r.json())
.then((body) => {
const { items, hasMore } = body.data as PaginatedData<RawDump>;
const { items, hasMore } = body.data as PaginatedData<Wire<Dump>>;
setDumpsState((s) =>
s.status === "loaded"
? {

View File

@@ -16,18 +16,16 @@ import type {
DumpUpvotedData,
Notification,
NotificationData,
PaginatedData,
PlaylistDumpAddedData,
PlaylistFollowedData,
RawNotification,
UserDumpPostedData,
UserFollowedData,
UserMentionedData,
} from "../model.ts";
import { deserializeNotification } from "../model.ts";
} from "../../shared/notification.ts";
import type { PaginatedData, Wire } from "../../shared/api.ts";
import { deserializeNotification } from "../utils/shared/deserialize.ts";
import { PageShell } from "../components/layout/PageShell.tsx";
import { friendlyFetchError } from "../utils/shared/api.ts";
import { expectOk } from "../utils/shared/api.ts";
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
type State =
// `arrived`: sent over the socket before the list came back — the list may
@@ -278,7 +276,7 @@ export function Notifications() {
let cancelled = false;
(async () => {
try {
const data = await expectOk<PaginatedData<RawNotification>>(
const data = await expectOk<PaginatedData<Wire<Notification>>>(
await authFetch(
`${API_URL}/api/notifications?page=1&limit=${NOTIFICATIONS_PAGE_SIZE}`,
),
@@ -362,7 +360,7 @@ export function Notifications() {
)
.then((r) => r.json())
.then((body) => {
const data = body.data as PaginatedData<RawNotification>;
const data = body.data as PaginatedData<Wire<Notification>>;
setState((s) =>
s.status === "loaded"
? {

View File

@@ -8,22 +8,22 @@ import {
import { Link, useNavigate, useParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, VALIDATION } from "../config/api.ts";
import { API_URL } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import { CountedInput } from "../components/shared/CountedInput.tsx";
import type {
Playlist,
PlaylistWithDumps,
RawDump,
RawPlaylist,
RawPlaylistWithDumps,
ReorderPlaylistRequest,
UpdatePlaylistRequest,
} from "../model.ts";
} from "../../shared/playlist.ts";
import type { Wire } from "../../shared/api.ts";
import type { Dump } from "../../shared/dump.ts";
import {
deserializeDump,
deserializePlaylist,
deserializePlaylistWithDumps,
} from "../model.ts";
} from "../utils/shared/deserialize.ts";
import { playlistImageUrl, playlistUrl } from "../utils/shared/urls.ts";
import { can } from "../utils/auth/permissions.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
@@ -41,9 +41,8 @@ import { Markdown } from "../components/editor/Markdown.tsx";
import { TextEditor } from "../components/editor/TextEditor.tsx";
import { FollowPlaylistButton } from "../components/social/FollowButton.tsx";
import { Tooltip } from "../components/shared/Tooltip.tsx";
import { friendlyFetchError } from "../utils/shared/api.ts";
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
import { Controller, FormProvider } from "react-hook-form";
import { expectOk } from "../utils/shared/api.ts";
import { FormError } from "../components/form/FormError.tsx";
import { SubmitButton } from "../components/form/SubmitButton.tsx";
import { useApiForm } from "../hooks/form/useApiForm.ts";
@@ -153,7 +152,7 @@ export function PlaylistDetail() {
.then((body) => {
if (!body.success) throw new Error("Failed to load playlist");
const pl = deserializePlaylistWithDumps(
body.data as RawPlaylistWithDumps,
body.data as Wire<PlaylistWithDumps>,
);
setState({ status: "loaded", playlist: pl });
const ids = new Set(pl.dumps.map((d) => d.id));
@@ -289,7 +288,7 @@ export function PlaylistDetail() {
.then((r) => r.ok ? r.json() : null)
.then((body) => {
if (!body?.success) return;
const dump = deserializeDump(body.data as RawDump);
const dump = deserializeDump(body.data as Wire<Dump>);
setState((s) => {
if (s.status !== "loaded") return s;
if (s.playlist.dumps.some((d) => d.id === dump.id)) return s;
@@ -835,7 +834,7 @@ function PlaylistEditForm(
const onSubmit = form.submit(
async ({ title, description, isPublic, image }) => {
const updated = deserializePlaylist(
await expectOk<RawPlaylist>(
await expectOk<Wire<Playlist>>(
await authFetch(`${API_URL}/api/playlists/${playlist.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
@@ -858,7 +857,7 @@ function PlaylistEditForm(
// The upload answers with the playlist as it now stands (new cover,
// new updatedAt), which is what the page should show.
onSaved(deserializePlaylist(
await expectOk<RawPlaylist>(
await expectOk<Wire<Playlist>>(
await authFetch(`${API_URL}/api/playlists/${playlist.id}/image`, {
method: "POST",
body: fd,

View File

@@ -3,7 +3,8 @@ import { Link, useNavigate, useSearchParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, VALIDATION } from "../config/api.ts";
import { API_URL } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { PageShell } from "../components/layout/PageShell.tsx";
import { expectOk } from "../utils/shared/api.ts";

View File

@@ -16,13 +16,11 @@ import {
deserializeDump,
deserializePlaylist,
deserializePublicUser,
type Dump,
type Playlist,
type PublicUser,
type RawDump,
type RawPlaylist,
type RawPublicUser,
} from "../model.ts";
} from "../utils/shared/deserialize.ts";
import type { Dump } from "../../shared/dump.ts";
import type { Playlist } from "../../shared/playlist.ts";
import type { PublicUser } from "../../shared/user.ts";
import type { Wire } from "../../shared/api.ts";
import { DEFAULT_PAGE_SIZE, SEARCH_URL } from "../config/api.ts";
import { friendlyFetchError } from "../utils/shared/api.ts";
@@ -95,9 +93,9 @@ export function Search() {
const body = await res.json() as {
success: true;
data: {
dumps: { items: RawDump[]; total: number; hasMore: boolean };
users: RawPublicUser[];
playlists: RawPlaylist[];
dumps: { items: Wire<Dump>[]; total: number; hasMore: boolean };
users: Wire<PublicUser>[];
playlists: Wire<Playlist>[];
};
};

View File

@@ -4,11 +4,9 @@ import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../config/api.ts";
import {
deserializeAuthResponse,
type LoginRequest,
type RawAuthResponse,
} from "../model.ts";
import { deserializeAuthResponse } from "../utils/shared/deserialize.ts";
import type { AuthResponse, LoginUserRequest } from "../../shared/user.ts";
import type { Wire } from "../../shared/api.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { useHeightTransition } from "../hooks/shared/useHeightTransition.ts";
@@ -41,11 +39,11 @@ export function UserLogin() {
});
const onSubmit = form.submit(async ({ username, password }) => {
const data = await expectOk<RawAuthResponse>(
const data = await expectOk<Wire<AuthResponse>>(
await fetch(`${API_URL}/api/users/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password } satisfies LoginRequest),
body: JSON.stringify({ username, password } satisfies LoginUserRequest),
}),
);
login(deserializeAuthResponse(data));

View File

@@ -10,18 +10,15 @@ import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, DEFAULT_PAGE_SIZE } from "../config/api.ts";
import { friendlyFetchError } from "../utils/shared/api.ts";
import type {
PaginatedData,
Playlist,
PublicUser,
RawPlaylist,
} from "../model.ts";
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
import type { PaginatedData, Wire } from "../../shared/api.ts";
import type { Playlist } from "../../shared/playlist.ts";
import type { PublicUser } from "../../shared/user.ts";
import {
deserializePlaylist,
deserializePublicUser,
hydratePlaylist,
} from "../model.ts";
} from "../utils/shared/deserialize.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { useWS } from "../hooks/ws/useWS.ts";
@@ -37,7 +34,6 @@ import { ConfirmModal } from "../components/shared/ConfirmModal.tsx";
import { PageShell } from "../components/layout/PageShell.tsx";
import { PageError } from "../components/layout/PageError.tsx";
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
import { expectOk } from "../utils/shared/api.ts";
interface PlaylistFeed {
items: Playlist[];
@@ -178,10 +174,10 @@ export function UserPlaylists() {
.then(([userBody, createdBody, followedBody]) => {
if (!userBody.success) throw new Error("User not found");
const createdData = createdBody.success
? createdBody.data as PaginatedData<RawPlaylist>
? createdBody.data as PaginatedData<Wire<Playlist>>
: { items: [], hasMore: false };
const followedData = followedBody.success
? followedBody.data as PaginatedData<RawPlaylist>
? followedBody.data as PaginatedData<Wire<Playlist>>
: { items: [], hasMore: false };
setState({
status: "loaded",
@@ -220,7 +216,7 @@ export function UserPlaylists() {
)
.then((r) => r.json())
.then((body) => {
const { items, hasMore } = body.data as PaginatedData<RawPlaylist>;
const { items, hasMore } = body.data as PaginatedData<Wire<Playlist>>;
setState((s) =>
s.status === "loaded"
? {
@@ -260,7 +256,7 @@ export function UserPlaylists() {
)
.then((r) => r.json())
.then((body) => {
const { items, hasMore } = body.data as PaginatedData<RawPlaylist>;
const { items, hasMore } = body.data as PaginatedData<Wire<Playlist>>;
setState((s) =>
s.status === "loaded"
? {

View File

@@ -10,26 +10,31 @@ import { Link, useNavigate, useParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, DEFAULT_PAGE_SIZE, VALIDATION } from "../config/api.ts";
import { API_URL, DEFAULT_PAGE_SIZE } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import type { Dump } from "../../shared/dump.ts";
import type {
Dump,
InviteTreeEntry,
PaginatedData,
Invitee,
PublicUser,
Role,
} from "../model.ts";
SelfUser,
UpdateUserRequest,
} from "../../shared/user.ts";
import type { PaginatedData, Wire } from "../../shared/api.ts";
import {
deserializeDump,
deserializeInviteTreeEntry,
deserializeInvitee,
deserializePlaylist,
deserializePublicUser,
deserializeSelfUser,
hydrateDump,
hydratePlaylist,
} from "../utils/shared/deserialize.ts";
import {
expectOk,
friendlyFetchError,
parseAPIResponse,
type RawDump,
type RawInviteTreeEntry,
type RawPublicUser,
type UpdateUserRequest,
} from "../model.ts";
} from "../utils/shared/api.ts";
import { Avatar } from "../components/shared/Avatar.tsx";
import { DumpCard } from "../components/dump/DumpCard.tsx";
import { PlaylistCard } from "../components/playlist/PlaylistCard.tsx";
@@ -49,13 +54,11 @@ import { useFading } from "../hooks/feed/useFading.ts";
import { useHeightTransition } from "../hooks/shared/useHeightTransition.ts";
import { usePlaylistListSync } from "../hooks/playlist/usePlaylistListSync.ts";
import { usePositionAwareSync } from "../hooks/feed/usePositionAwareSync.ts";
import type { Playlist, RawPlaylist } from "../model.ts";
import { deserializePlaylist } from "../model.ts";
import type { Playlist } from "../../shared/playlist.ts";
import { useFeedCache } from "../hooks/feed/useFeedCache.ts";
import { DumpCreateModal } from "../components/dump/create/DumpCreateModal.tsx";
import { FollowUserButton } from "../components/social/FollowButton.tsx";
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
import { friendlyFetchError } from "../utils/shared/api.ts";
import { can } from "../utils/auth/permissions.ts";
import { TextEditor } from "../components/editor/TextEditor.tsx";
import { Markdown } from "../components/editor/Markdown.tsx";
@@ -63,7 +66,6 @@ import { ChangePasswordModal } from "../components/profile/ChangePasswordModal.t
import { TabBar } from "../components/shared/TabBar.tsx";
import { useTabParam } from "../hooks/shared/useTabParam.ts";
import { Controller, FormProvider } from "react-hook-form";
import { expectOk } from "../utils/shared/api.ts";
import { FormError } from "../components/form/FormError.tsx";
import { SubmitButton } from "../components/form/SubmitButton.tsx";
import { useApiForm } from "../hooks/form/useApiForm.ts";
@@ -206,9 +208,9 @@ type InviteTreeState =
| null
| { status: "loading" }
| { status: "error"; error: string }
| { status: "loaded"; entries: InviteTreeEntry[] };
| { status: "loaded"; entries: Invitee[] };
type InviteTreeNode = InviteTreeEntry & { children: InviteTreeNode[] };
type InviteTreeNode = Invitee & { children: InviteTreeNode[] };
const PROFILE_TABS = [
"dumps",
"playlists",
@@ -220,7 +222,7 @@ const PROFILE_TABS = [
type ProfileTab = (typeof PROFILE_TABS)[number];
function buildInviteTree(
entries: InviteTreeEntry[],
entries: Invitee[],
parentId: string,
): InviteTreeNode[] {
return entries
@@ -484,13 +486,14 @@ export function UserPublicProfile() {
playlistsRes.json(),
]);
const votesData: PaginatedData<RawDump> = votesBody.success
const votesData: PaginatedData<Wire<Dump>> = votesBody.success
? votesBody.data
: { items: [], hasMore: false };
const playlistsData: PaginatedData<RawPlaylist> = playlistsBody.success
? playlistsBody.data
: { items: [], hasMore: false };
const dumpsData: PaginatedData<RawDump> = dumpsBody.success
const playlistsData: PaginatedData<Wire<Playlist>> =
playlistsBody.success
? playlistsBody.data
: { items: [], hasMore: false };
const dumpsData: PaginatedData<Wire<Dump>> = dumpsBody.success
? dumpsBody.data
: { items: [], hasMore: false };
@@ -641,10 +644,10 @@ export function UserPublicProfile() {
.then(([ur, pr]) => Promise.all([ur.json(), pr.json()]))
.then(([ub, pb]) => {
const usersData = ub.success
? ub.data as PaginatedData<RawPublicUser>
? ub.data as PaginatedData<Wire<PublicUser>>
: { items: [], hasMore: false };
const playlistsData = pb.success
? pb.data as PaginatedData<RawPlaylist>
? pb.data as PaginatedData<Wire<Playlist>>
: { items: [], hasMore: false };
setFollowedState({
status: "loaded",
@@ -684,8 +687,8 @@ export function UserPublicProfile() {
)
.then((r) => r.json())
.then((body) => {
const entries: InviteTreeEntry[] = body.success
? (body.data as RawInviteTreeEntry[]).map(deserializeInviteTreeEntry)
const entries: Invitee[] = body.success
? (body.data as Wire<Invitee>[]).map(deserializeInvitee)
: [];
setInviteTreeState({ status: "loaded", entries });
})
@@ -715,7 +718,7 @@ export function UserPublicProfile() {
fetch(
`${API_URL}/api/users/${username}/followed-users?page=${nextPage}&limit=${DEFAULT_PAGE_SIZE}`,
)
.then(expectOk<PaginatedData<RawPublicUser>>)
.then(expectOk<PaginatedData<Wire<PublicUser>>>)
.then(({ items, hasMore }) =>
setUsers((u) => ({
items: [...u.items, ...items.map(deserializePublicUser)],
@@ -752,20 +755,17 @@ export function UserPublicProfile() {
method: "POST",
body: formData,
});
const body = parseAPIResponse<RawPublicUser>(await res.json());
const body = parseAPIResponse<Wire<SelfUser>>(await res.json());
if (!body.success) {
setAvatarError(body.error.message);
return;
}
updateSession({ user: deserializePublicUser(body.data) });
const user = deserializeSelfUser(body.data);
updateSession({ user });
setState((prev) =>
prev.status === "loaded"
? { ...prev, user: deserializePublicUser(body.data) }
: prev
);
setState((prev) => prev.status === "loaded" ? { ...prev, user } : prev);
} catch {
setAvatarError(t`Upload failed`);
} finally {
@@ -1728,7 +1728,7 @@ function RoleSwitcher({ userId, currentRole, onSaved }: RoleSwitcherProps) {
method: "PATCH",
body: JSON.stringify({ role }),
});
const body = parseAPIResponse<RawPublicUser>(await res.json());
const body = parseAPIResponse<Wire<PublicUser>>(await res.json());
if (!body.success) {
setError(body.error.message);
return;
@@ -1781,7 +1781,7 @@ function EmailEditor({ initialEmail, onCancel, onSaved }: EmailEditorProps) {
const submitting = form.formState.isSubmitting;
const onSubmit = form.submit(async ({ email }) => {
await expectOk<RawPublicUser>(
await expectOk<Wire<PublicUser>>(
await authFetch(`${API_URL}/api/users/me`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -1848,7 +1848,7 @@ function DescriptionEditor(
const onSubmit = form.submit(async ({ description }) => {
const trimmed = description.trim();
// Sent even when empty: left out, the server would keep the old one.
await expectOk<RawPublicUser>(
await expectOk<Wire<PublicUser>>(
await authFetch(`${API_URL}/api/users/me`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },

View File

@@ -3,12 +3,11 @@ import { Link, useNavigate, useSearchParams } from "react-router";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL, VALIDATION } from "../config/api.ts";
import {
deserializeAuthResponse,
type RawAuthResponse,
type RegisterRequest,
} from "../model.ts";
import { API_URL } from "../config/api.ts";
import { VALIDATION } from "../../shared/validation.ts";
import { deserializeAuthResponse } from "../utils/shared/deserialize.ts";
import type { Wire } from "../../shared/api.ts";
import type { AuthResponse, RegisterUserRequest } from "../../shared/user.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { PageShell } from "../components/layout/PageShell.tsx";
@@ -62,7 +61,7 @@ export function UserRegister() {
}, [token]);
const onSubmit = form.submit(async ({ username, email, password }) => {
const data = await expectOk<RawAuthResponse>(
const data = await expectOk<Wire<AuthResponse>>(
await fetch(`${API_URL}/api/users/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -72,7 +71,7 @@ export function UserRegister() {
password,
inviteToken: token,
email,
} satisfies RegisterRequest,
} satisfies RegisterUserRequest,
),
}),
);

View File

@@ -4,8 +4,8 @@ import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { API_URL } from "../config/api.ts";
import type { Dump } from "../model.ts";
import { deserializeDump } from "../model.ts";
import type { Dump } from "../../shared/dump.ts";
import { deserializeDump } from "../utils/shared/deserialize.ts";
import { useAuth } from "../hooks/auth/useAuth.ts";
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
import { useWS } from "../hooks/ws/useWS.ts";