75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
import ky, { HTTPError, KyInstance } from "ky";
|
|
import { CorpConfig } from "../config/types.js";
|
|
import { clearSealToken, getSealSessionForCorp } from "../auth/seal.js";
|
|
import { resolveSealCustomHeaders } from "./request-headers.js";
|
|
|
|
function formatErrorData(data: unknown): string {
|
|
if (data === undefined || data === null || data === "") return "";
|
|
if (typeof data === "string") return data;
|
|
try {
|
|
return JSON.stringify(data);
|
|
} catch {
|
|
return String(data);
|
|
}
|
|
}
|
|
|
|
function withResponseBody(error: unknown): Error {
|
|
if (!(error instanceof HTTPError)) return error as Error;
|
|
const body = formatErrorData(error.data);
|
|
if (body) error.message = `${error.message}: ${body}`;
|
|
return error;
|
|
}
|
|
|
|
function createBeforeErrorHook(corpId?: string) {
|
|
return async ({ error }: { error: unknown }) => {
|
|
if (corpId && error instanceof HTTPError && error.response.status === 401) {
|
|
clearSealToken(corpId);
|
|
}
|
|
return withResponseBody(error);
|
|
};
|
|
}
|
|
|
|
export async function createSealClient(corp: CorpConfig): Promise<KyInstance> {
|
|
const session = await getSealSessionForCorp(corp);
|
|
|
|
return ky.create({
|
|
prefix: session.enterprise.sealUrl,
|
|
timeout: 30000,
|
|
headers: {
|
|
...resolveSealCustomHeaders(corp.seal),
|
|
Authorization: `Bearer ${session.token}`
|
|
},
|
|
hooks: {
|
|
beforeError: [createBeforeErrorHook(corp.id)]
|
|
}
|
|
});
|
|
}
|
|
|
|
export async function createSealClientForToken(corp: CorpConfig, token: string): Promise<KyInstance> {
|
|
const session = await getSealSessionForCorp(corp);
|
|
|
|
return createSealClientForUrl(session.enterprise.sealUrl, token, resolveSealCustomHeaders(corp.seal));
|
|
}
|
|
|
|
export function createSealClientForUrl(
|
|
sealUrl: string,
|
|
token?: string,
|
|
customHeaders: Record<string, string> = {}
|
|
): KyInstance {
|
|
const headers: Record<string, string> = {
|
|
...customHeaders
|
|
};
|
|
if (token) {
|
|
headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
|
|
return ky.create({
|
|
prefix: sealUrl.replace(/\/+$/, ""),
|
|
timeout: 30000,
|
|
headers,
|
|
hooks: {
|
|
beforeError: [createBeforeErrorHook()]
|
|
}
|
|
});
|
|
}
|