feat: submit batches to status backend
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import type { BatchPayload } from "../content/market/batch-payload";
|
||||
import { isAuthResponseMessage } from "./auth-messages";
|
||||
import { DEFAULT_BATCH_SUBMIT_BASE_URL } from "./batch-submit-config";
|
||||
|
||||
interface FetchResponseLike {
|
||||
json(): Promise<unknown>;
|
||||
@@ -16,11 +17,12 @@ type GetAccessTokenLike = () => Promise<string>;
|
||||
type SendMessageLike = (message: unknown) => Promise<unknown>;
|
||||
|
||||
export function createBatchSubmitClient(options: {
|
||||
baseUrl: string;
|
||||
baseUrl?: string;
|
||||
fetchImpl?: FetchLike;
|
||||
getAccessToken?: GetAccessTokenLike;
|
||||
sendMessage: SendMessageLike;
|
||||
}) {
|
||||
const baseUrl = options.baseUrl ?? DEFAULT_BATCH_SUBMIT_BASE_URL;
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
const getAccessToken =
|
||||
options.getAccessToken ?? (() => readAccessToken(options.sendMessage));
|
||||
@@ -29,7 +31,7 @@ export function createBatchSubmitClient(options: {
|
||||
async submitBatch(payload: BatchPayload) {
|
||||
const token = await getAccessToken();
|
||||
const response = await fetchImpl(
|
||||
new URL("/api/mock/batches", options.baseUrl).toString(),
|
||||
buildBatchSubmitUrl(baseUrl),
|
||||
{
|
||||
body: JSON.stringify(payload),
|
||||
headers: {
|
||||
@@ -48,11 +50,15 @@ export function createBatchSubmitClient(options: {
|
||||
throw new Error(`batch submit failed: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
return readBatchSubmitResponse(await response.json());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function buildBatchSubmitUrl(baseUrl: string): string {
|
||||
return new URL("/api/v1/batch-status/batches", baseUrl).toString();
|
||||
}
|
||||
|
||||
async function readAccessToken(sendMessage: SendMessageLike): Promise<string> {
|
||||
const response = await sendMessage({ type: "auth:get-access-token" });
|
||||
|
||||
@@ -67,3 +73,23 @@ async function readAccessToken(sendMessage: SendMessageLike): Promise<string> {
|
||||
|
||||
return response.value.accessToken;
|
||||
}
|
||||
|
||||
function readBatchSubmitResponse(payload: unknown): unknown {
|
||||
if (!isRecord(payload)) {
|
||||
throw new Error("batch submit response is invalid");
|
||||
}
|
||||
|
||||
if (payload.success !== true) {
|
||||
const message =
|
||||
typeof payload.msg === "string" && payload.msg.trim()
|
||||
? payload.msg
|
||||
: "batch submit failed";
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return "data" in payload ? payload.data : payload;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export const DEFAULT_BATCH_SUBMIT_BASE_URL = "http://192.168.31.29:8083";
|
||||
Reference in New Issue
Block a user