feat: add batch submit client
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import type { BatchPayload } from "../content/market/batch-payload";
|
||||
import { isAuthResponseMessage } from "./auth-messages";
|
||||
|
||||
interface FetchResponseLike {
|
||||
json(): Promise<unknown>;
|
||||
ok: boolean;
|
||||
status: number;
|
||||
}
|
||||
|
||||
type FetchLike = (
|
||||
input: string,
|
||||
init?: RequestInit
|
||||
) => Promise<FetchResponseLike>;
|
||||
|
||||
type SendMessageLike = (message: unknown) => Promise<unknown>;
|
||||
|
||||
export function createBatchSubmitClient(options: {
|
||||
baseUrl: string;
|
||||
fetchImpl?: FetchLike;
|
||||
sendMessage: SendMessageLike;
|
||||
}) {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
|
||||
return {
|
||||
async submitBatch(payload: BatchPayload) {
|
||||
const token = await readAccessToken(options.sendMessage);
|
||||
const response = await fetchImpl(
|
||||
new URL("/api/mock/batches", options.baseUrl).toString(),
|
||||
{
|
||||
body: JSON.stringify(payload),
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
method: "POST"
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new Error("batch submit unauthorized");
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`batch submit failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readAccessToken(sendMessage: SendMessageLike): Promise<string> {
|
||||
const response = await sendMessage({ type: "auth:get-access-token" });
|
||||
|
||||
if (
|
||||
!isAuthResponseMessage(response) ||
|
||||
!response.ok ||
|
||||
response.type !== "auth:token" ||
|
||||
!response.value.accessToken.trim()
|
||||
) {
|
||||
throw new Error("batch submit token unavailable");
|
||||
}
|
||||
|
||||
return response.value.accessToken;
|
||||
}
|
||||
Reference in New Issue
Block a user