Files
Dorod-Sky/skyvern-frontend/src/api/AxiosClient.ts

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-04-15 11:54:12 -07:00
import { apiBaseUrl, artifactApiBaseUrl, envCredential } from "@/util/env";
2024-04-01 21:34:52 +03:00
import axios from "axios";
2025-01-15 11:41:31 -08:00
const apiV1BaseUrl = apiBaseUrl;
const apiV2BaseUrl = apiBaseUrl.replace("v1", "v2");
2024-04-01 21:34:52 +03:00
const client = axios.create({
2025-01-15 11:41:31 -08:00
baseURL: apiV1BaseUrl,
headers: {
"Content-Type": "application/json",
"x-api-key": envCredential,
},
});
const v2Client = axios.create({
baseURL: apiV2BaseUrl,
2024-04-01 21:34:52 +03:00
headers: {
"Content-Type": "application/json",
2024-04-15 11:54:12 -07:00
"x-api-key": envCredential,
2024-04-01 21:34:52 +03:00
},
});
const artifactApiClient = axios.create({
baseURL: artifactApiBaseUrl,
});
2024-04-15 11:54:12 -07:00
export function setAuthorizationHeader(token: string) {
client.defaults.headers.common["Authorization"] = `Bearer ${token}`;
2025-01-15 11:41:31 -08:00
v2Client.defaults.headers.common["Authorization"] = `Bearer ${token}`;
2024-04-15 11:54:12 -07:00
}
export function removeAuthorizationHeader() {
2024-05-07 11:31:05 -07:00
if (client.defaults.headers.common["Authorization"]) {
delete client.defaults.headers.common["Authorization"];
2025-01-15 11:41:31 -08:00
delete v2Client.defaults.headers.common["Authorization"];
2024-05-07 11:31:05 -07:00
}
2024-04-15 11:54:12 -07:00
}
export function setApiKeyHeader(apiKey: string) {
client.defaults.headers.common["X-API-Key"] = apiKey;
2025-01-15 11:41:31 -08:00
v2Client.defaults.headers.common["X-API-Key"] = apiKey;
2024-04-15 11:54:12 -07:00
}
export function removeApiKeyHeader() {
2024-05-07 11:31:05 -07:00
if (client.defaults.headers.common["X-API-Key"]) {
delete client.defaults.headers.common["X-API-Key"];
}
2025-01-15 11:41:31 -08:00
if (v2Client.defaults.headers.common["X-API-Key"]) {
delete v2Client.defaults.headers.common["X-API-Key"];
}
2024-04-15 11:54:12 -07:00
}
2025-01-15 11:41:31 -08:00
async function getClient(
credentialGetter: CredentialGetter | null,
version: string = "v1",
) {
2024-05-07 11:31:05 -07:00
if (credentialGetter) {
removeApiKeyHeader();
const credential = await credentialGetter();
if (!credential) {
console.warn("No credential found");
2025-01-15 11:41:31 -08:00
return version === "v1" ? client : v2Client;
2024-05-07 11:31:05 -07:00
}
setAuthorizationHeader(credential);
}
2025-01-15 11:41:31 -08:00
return version === "v1" ? client : v2Client;
2024-05-07 11:31:05 -07:00
}
export type CredentialGetter = () => Promise<string | null>;
export { getClient, artifactApiClient };