Files
frontend-helper/src/lib/post-create.ts
T

95 lines
3.3 KiB
TypeScript

import { FEED_BASE_URL } from "./env";
import { ensureFreshSession, refreshSession } from "./session-refresh";
// Text-post creation proxy. Two feed calls with the person's server-held feed
// token: create a public draft, then publish it with the same content. Neither
// the token nor the post text is logged.
export type CreatePostResult =
| { ok: true; id: string; status: string | null }
| { ok: false; status: 400 | 401 | 502; error: "sign_in" | "empty_post" | "post_failed" };
interface CreateOptions {
fetchImpl?: typeof fetch;
now?: number;
}
export const MAX_POST_LENGTH = 20_000;
function rec(v: unknown): Record<string, unknown> {
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
}
function readCreated(body: unknown): { id: string; status: string | null } | null {
const root = rec(body);
const data = rec(root.data);
const post = rec(data.post);
for (const v of [data.id, post.id, root.id]) {
if ((typeof v === "string" && v) || typeof v === "number") {
const status = [data.status, post.status, root.status].find((s) => typeof s === "string");
return { id: String(v), status: (status as string | undefined) ?? null };
}
}
return null;
}
function send(token: string, path: string, payload: unknown, doFetch: typeof fetch) {
return doFetch(`${FEED_BASE_URL}${path}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(payload),
});
}
export async function createTextPost(
sessionId: string | undefined,
content: unknown,
options: CreateOptions = {},
): Promise<CreatePostResult> {
const signIn = { ok: false, status: 401, error: "sign_in" } as const;
const failed = { ok: false, status: 502, error: "post_failed" } as const;
const doFetch = options.fetchImpl ?? fetch;
let session = await ensureFreshSession(sessionId, options);
if (!session || !sessionId) return signIn;
if (typeof content !== "string" || !content.trim() || content.length > MAX_POST_LENGTH) {
return { ok: false, status: 400, error: "empty_post" };
}
// One call with a single refresh-and-retry on a 401 token rejection.
const call = async (path: string, payload: unknown): Promise<Response | "sign_in"> => {
let res = await send(session!.feedAccessToken, path, payload, doFetch);
if (res.status === 401) {
session = await refreshSession(sessionId, options);
if (!session) return "sign_in";
res = await send(session.feedAccessToken, path, payload, doFetch);
if (res.status === 401) return "sign_in";
}
return res;
};
try {
const created = await call("/api/v1/posts", {
content,
type: "text",
status: "draft",
visibility: "public",
});
if (created === "sign_in") return signIn;
if (created.status !== 200 && created.status !== 201) return failed;
const info = readCreated(await created.json().catch(() => null));
if (!info) return failed;
const published = await call(`/api/v1/posts/${encodeURIComponent(info.id)}/publish`, { content });
if (published === "sign_in") return signIn;
if (published.status < 200 || published.status > 299) return failed;
return { ok: true, id: info.id, status: info.status };
} catch {
return failed;
}
}