53 lines
1.8 KiB
TypeScript
53 lines
1.8 KiB
TypeScript
import { FEED_BASE_URL } from "./env";
|
|
import { ensureFreshSession, refreshSession } from "./session-refresh";
|
|
|
|
// Delete proxy: feed DELETE /api/v1/posts/{id} with the person's server-held
|
|
// feed token. The feed decides whether the caller may delete; this app also
|
|
// only offers the control on the person's own posts. One refresh-and-retry
|
|
// after a 401 token rejection.
|
|
|
|
export type DeleteResult =
|
|
| { ok: true }
|
|
| { ok: false; status: 400 | 401 | 502; error: "sign_in" | "bad_post" | "delete_failed" };
|
|
|
|
interface DeleteOptions {
|
|
fetchImpl?: typeof fetch;
|
|
now?: number;
|
|
}
|
|
|
|
const POST_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
|
|
function call(token: string, postId: string, doFetch: typeof fetch) {
|
|
return doFetch(`${FEED_BASE_URL}/api/v1/posts/${encodeURIComponent(postId)}`, {
|
|
method: "DELETE",
|
|
headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
|
|
});
|
|
}
|
|
|
|
export async function deletePost(
|
|
sessionId: string | undefined,
|
|
postId: string,
|
|
options: DeleteOptions = {},
|
|
): Promise<DeleteResult> {
|
|
const signIn = { ok: false, status: 401, error: "sign_in" } as const;
|
|
const failed = { ok: false, status: 502, error: "delete_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" };
|
|
|
|
try {
|
|
let res = await call(session.feedAccessToken, postId, doFetch);
|
|
if (res.status === 401) {
|
|
session = await refreshSession(sessionId, options);
|
|
if (!session) return signIn;
|
|
res = await call(session.feedAccessToken, postId, doFetch);
|
|
if (res.status === 401) return signIn;
|
|
}
|
|
return res.status === 200 ? { ok: true } : failed;
|
|
} catch {
|
|
return failed;
|
|
}
|
|
}
|