3dom4wf7p: Publish public text posts from a feed composer
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
// Browser-side text-post publishing. The composer text is only cleared after
|
||||
// the new post id shows up on the reloaded first page of the home feed.
|
||||
|
||||
import { fetchFeedPage, FeedLoadError, type FeedPage } from "./feed-client";
|
||||
|
||||
export class PostError extends Error {
|
||||
constructor(public readonly signedOut: boolean) {
|
||||
super(signedOut ? "sign_in" : "publish_failed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function sendPost(content: string, fetchImpl: typeof fetch = fetch): Promise<string> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl("/api/posts", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ content }),
|
||||
});
|
||||
} catch {
|
||||
throw new PostError(false);
|
||||
}
|
||||
if (res.status === 401) throw new PostError(true);
|
||||
if (!res.ok) throw new PostError(false);
|
||||
try {
|
||||
const b = (await res.json()) as { id?: unknown };
|
||||
if ((typeof b.id === "string" && b.id) || typeof b.id === "number") return String(b.id);
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
throw new PostError(false);
|
||||
}
|
||||
|
||||
function pageHasPost(page: FeedPage, id: string): boolean {
|
||||
return page.items.some((item) => {
|
||||
const post = (item as { post?: { id?: unknown } } | null)?.post;
|
||||
return post != null && String(post.id) === id;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload the first page. Returns the page when it holds the post id, else null.
|
||||
* Throws PostError when the person is signed out or the reload fails.
|
||||
*/
|
||||
export async function confirmOnFirstPage(
|
||||
id: string,
|
||||
fetchPage: (cursor: string | null) => Promise<FeedPage> = fetchFeedPage,
|
||||
): Promise<FeedPage | null> {
|
||||
try {
|
||||
const page = await fetchPage(null);
|
||||
return pageHasPost(page, id) ? page : null;
|
||||
} catch (e) {
|
||||
throw new PostError(e instanceof FeedLoadError && e.signedOut);
|
||||
}
|
||||
}
|
||||
|
||||
export interface PublishDeps {
|
||||
send?: (content: string) => Promise<string>;
|
||||
fetchPage?: (cursor: string | null) => Promise<FeedPage>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish text and confirm it on the reloaded first page. Returns that page
|
||||
* only when the post id is on it. `unconfirmed` holds an id that was created
|
||||
* earlier but not yet seen, so a retry re-checks the feed and does not create
|
||||
* a duplicate. Throws PostError otherwise; the caller keeps the composer text.
|
||||
*/
|
||||
export async function publishAndConfirm(
|
||||
content: string,
|
||||
unconfirmed: { id: string | null },
|
||||
deps: PublishDeps = {},
|
||||
): Promise<FeedPage> {
|
||||
const id = unconfirmed.id ?? (await (deps.send ?? sendPost)(content));
|
||||
unconfirmed.id = id;
|
||||
const page = await confirmOnFirstPage(id, deps.fetchPage);
|
||||
if (!page) throw new PostError(false);
|
||||
unconfirmed.id = null;
|
||||
return page;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user