64 lines
1.3 KiB
JavaScript
64 lines
1.3 KiB
JavaScript
function buildRequestUrl({ baseUrl, method, version }) {
|
|
const url = new URL(baseUrl);
|
|
const timestamp = String(Math.floor(Date.now() / 1000));
|
|
url.searchParams.set("method", method);
|
|
url.searchParams.set("v", version);
|
|
url.searchParams.set("timestamp", timestamp);
|
|
return url;
|
|
}
|
|
|
|
function withTimeoutSignal(timeoutMs) {
|
|
return AbortSignal.timeout(timeoutMs);
|
|
}
|
|
|
|
export async function crawlApi({
|
|
baseUrl,
|
|
version,
|
|
method,
|
|
body = {},
|
|
timeoutMs = 20000,
|
|
token = null,
|
|
}) {
|
|
const url = buildRequestUrl({ baseUrl, method, version });
|
|
const headers = {
|
|
"content-type": "application/json",
|
|
platform: "web",
|
|
project: "all",
|
|
};
|
|
if (token) {
|
|
headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
const response = await fetch(url, {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(body ?? {}),
|
|
signal: withTimeoutSignal(timeoutMs),
|
|
});
|
|
|
|
const rawText = await response.text();
|
|
let parsed;
|
|
try {
|
|
parsed = rawText ? JSON.parse(rawText) : null;
|
|
} catch {
|
|
parsed = {
|
|
rawText,
|
|
};
|
|
}
|
|
|
|
return {
|
|
request: {
|
|
url: url.toString(),
|
|
method,
|
|
body: body ?? {},
|
|
headers,
|
|
},
|
|
status: response.status,
|
|
ok: response.ok,
|
|
response: parsed,
|
|
};
|
|
}
|
|
|
|
export function extractToken(responseData) {
|
|
return responseData?.data?.token ?? null;
|
|
}
|