4wswt4ex2: Add like and unlike for post cards
This commit is contained in:
@@ -18,6 +18,8 @@ export interface CardPost {
|
||||
time: number;
|
||||
text: string;
|
||||
likesCount: number;
|
||||
/** Whether the signed-in person has liked the post. */
|
||||
isLiked: boolean;
|
||||
commentsCount: number;
|
||||
media: CardMedia[];
|
||||
}
|
||||
@@ -99,6 +101,7 @@ export function toCardPost(item: unknown, index = 0): CardPost | null {
|
||||
time: Number.isFinite(t) ? t : Number.NEGATIVE_INFINITY,
|
||||
text: typeof post.content === "string" ? post.content : "",
|
||||
likesCount: num(item.likesCount ?? post.likesCount),
|
||||
isLiked: post.isLiked === true || item.isLiked === true,
|
||||
commentsCount: num(item.commentsCount ?? post.commentsCount),
|
||||
media: toMedia(post.mediaItems),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Browser-side like / unlike calls and the pure card update they drive.
|
||||
|
||||
import type { CardPost } from "./feed-model";
|
||||
|
||||
export interface LikeOutcome {
|
||||
isLiked: boolean;
|
||||
likesCount: number | null;
|
||||
}
|
||||
|
||||
export class LikeError extends Error {
|
||||
constructor(public readonly signedOut: boolean) {
|
||||
super(signedOut ? "sign_in" : "like_failed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendLike(
|
||||
postId: string,
|
||||
liked: boolean,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<LikeOutcome> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl(`/api/posts/${encodeURIComponent(postId)}/like`, {
|
||||
method: liked ? "POST" : "DELETE",
|
||||
credentials: "same-origin",
|
||||
});
|
||||
} catch {
|
||||
throw new LikeError(false);
|
||||
}
|
||||
if (res.status === 401) throw new LikeError(true);
|
||||
if (!res.ok) throw new LikeError(false);
|
||||
try {
|
||||
const b = (await res.json()) as { isLiked?: unknown; likesCount?: unknown };
|
||||
return {
|
||||
isLiked: typeof b.isLiked === "boolean" ? b.isLiked : liked,
|
||||
likesCount:
|
||||
typeof b.likesCount === "number" && Number.isInteger(b.likesCount) && b.likesCount >= 0
|
||||
? b.likesCount
|
||||
: null,
|
||||
};
|
||||
} catch {
|
||||
throw new LikeError(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** The card after a successful call: the server count when present, else flip and adjust by one. */
|
||||
export function applyLikeOutcome(post: CardPost, wanted: boolean, out: LikeOutcome): CardPost {
|
||||
if (out.likesCount !== null) return { ...post, isLiked: out.isLiked, likesCount: out.likesCount };
|
||||
const changed = post.isLiked !== wanted;
|
||||
const delta = changed ? (wanted ? 1 : -1) : 0;
|
||||
return { ...post, isLiked: wanted, likesCount: Math.max(0, post.likesCount + delta) };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { FEED_BASE_URL } from "./env";
|
||||
import { ensureFreshSession, refreshSession } from "./session-refresh";
|
||||
|
||||
// Like / unlike proxy. One call to the feed per request, with the person's
|
||||
// server-held feed token. Like is idempotent: a like is never retried in a
|
||||
// loop. The only repeat is one refresh-and-retry after a 401 token rejection.
|
||||
|
||||
export type LikeResult =
|
||||
| { ok: true; isLiked: boolean; likesCount: number | null }
|
||||
| { ok: false; status: 400 | 401 | 502; error: "sign_in" | "bad_post" | "like_failed" };
|
||||
|
||||
interface LikeOptions {
|
||||
fetchImpl?: typeof fetch;
|
||||
now?: number;
|
||||
}
|
||||
|
||||
const POST_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
||||
|
||||
function call(token: string, postId: string, liked: boolean, doFetch: typeof fetch) {
|
||||
return doFetch(`${FEED_BASE_URL}/api/v1/posts/${encodeURIComponent(postId)}/like`, {
|
||||
method: liked ? "POST" : "DELETE",
|
||||
headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
|
||||
});
|
||||
}
|
||||
|
||||
function rec(v: unknown): Record<string, unknown> {
|
||||
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
|
||||
}
|
||||
|
||||
/** A like count from the response body, only when it is a non-negative integer. */
|
||||
function readCount(body: unknown): number | null {
|
||||
const root = rec(body);
|
||||
const data = rec(root.data);
|
||||
for (const v of [data.likesCount, data.likeCount, root.likesCount, root.likeCount]) {
|
||||
if (typeof v === "number" && Number.isInteger(v) && v >= 0) return v;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function setPostLike(
|
||||
sessionId: string | undefined,
|
||||
postId: string,
|
||||
liked: boolean,
|
||||
options: LikeOptions = {},
|
||||
): Promise<LikeResult> {
|
||||
const signIn = { ok: false, status: 401, error: "sign_in" } as const;
|
||||
const failed = { ok: false, status: 502, error: "like_failed" } as const;
|
||||
const doFetch = options.fetchImpl ?? fetch;
|
||||
|
||||
let session = await ensureFreshSession(sessionId, options);
|
||||
if (!session || !sessionId) return signIn;
|
||||
if (!POST_ID.test(postId)) return { ok: false, status: 400, error: "bad_post" };
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await call(session.feedAccessToken, postId, liked, doFetch);
|
||||
if (res.status === 401) {
|
||||
session = await refreshSession(sessionId, options);
|
||||
if (!session) return signIn;
|
||||
res = await call(session.feedAccessToken, postId, liked, doFetch);
|
||||
if (res.status === 401) return signIn;
|
||||
}
|
||||
} catch {
|
||||
return failed;
|
||||
}
|
||||
if (res.status !== 200) return failed;
|
||||
|
||||
let body: unknown = null;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
return failed;
|
||||
}
|
||||
if (rec(rec(body).data).success !== true) return failed;
|
||||
return { ok: true, isLiked: liked, likesCount: readCount(body) };
|
||||
}
|
||||
Reference in New Issue
Block a user