84 lines
4.4 KiB
TypeScript
84 lines
4.4 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
||
import { intuitTid, type FetchFn } from "./oauth.js";
|
||
|
||
/** Ошибка API QuickBooks: статус, разобранный Fault (код, сообщение, деталь) и intuit_tid для обращения в поддержку Intuit. */
|
||
export class QboApiError extends Error {
|
||
constructor(
|
||
message: string,
|
||
readonly status: number,
|
||
readonly faultType?: string,
|
||
readonly code?: string,
|
||
readonly detail?: string,
|
||
readonly intuitTid?: string,
|
||
) {
|
||
super(message);
|
||
}
|
||
/** Ошибка валидации запроса (4xx с Fault): повторять бессмысленно, нужно исправить данные. */
|
||
get isValidation(): boolean {
|
||
return this.status === 400 || this.faultType === "ValidationFault";
|
||
}
|
||
}
|
||
|
||
/** Разбор тела ошибки QuickBooks: { Fault: { type, Error: [{ Message, Detail, code }] } }. */
|
||
export function parseFault(body: unknown): { type?: string; code?: string; message?: string; detail?: string } {
|
||
const f = (body as { Fault?: { type?: string; Error?: Array<{ Message?: string; Detail?: string; code?: string }> } } | null)?.Fault;
|
||
if (!f) return {};
|
||
const e = f.Error?.[0];
|
||
return { type: f.type, code: e?.code, message: e?.Message, detail: e?.Detail };
|
||
}
|
||
|
||
export interface ApiDeps {
|
||
getToken(opts?: { force?: boolean }): Promise<{ accessToken: string; realmId: string; apiBase: string }>;
|
||
fetchFn: (url: string, init: { method: string; headers: Record<string, string>; body?: string }) => ReturnType<FetchFn>;
|
||
sleep?: (ms: number) => Promise<void>;
|
||
log?: (msg: string, extra?: Record<string, unknown>) => void;
|
||
/** Число попыток (401 - одна лишняя с обновлением токена, 429/5xx - с паузой). */
|
||
attempts?: number;
|
||
}
|
||
|
||
const MINOR_VERSION = 75;
|
||
|
||
/**
|
||
* Клиент API QuickBooks: Bearer, повтор после 401 с принудительным обновлением токена, повторы с паузой при 429/5xx,
|
||
* разбор Fault, захват intuit_tid (в лог каждой ошибки и в текст исключения), для записи - requestid (идемпотентность повторов).
|
||
*/
|
||
export class QboApi {
|
||
constructor(private readonly d: ApiDeps) {}
|
||
|
||
get(path: string): Promise<any> {
|
||
return this.request("GET", path);
|
||
}
|
||
|
||
/** Запись (создание/обновление объекта). Повторы безопасны благодаря requestid. */
|
||
post(path: string, body: unknown): Promise<any> {
|
||
return this.request("POST", path, body);
|
||
}
|
||
|
||
async request(method: "GET" | "POST", path: string, body?: unknown): Promise<any> {
|
||
const sleep = this.d.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||
const attempts = this.d.attempts ?? 5;
|
||
const shortPath = path.split("?")[0];
|
||
const requestId = method === "POST" ? randomUUID() : undefined;
|
||
let force = false;
|
||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||
const t = await this.d.getToken({ force });
|
||
let url = `${t.apiBase}/v3/company/${t.realmId}/${path}${path.includes("?") ? "&" : "?"}minorversion=${MINOR_VERSION}`;
|
||
if (requestId) url += `&requestid=${requestId}`;
|
||
const headers: Record<string, string> = { Authorization: "Bearer " + t.accessToken, Accept: "application/json" };
|
||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||
const r = await this.d.fetchFn(url, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
|
||
const tid = intuitTid(r);
|
||
if (r.ok) return r.json();
|
||
const fault = parseFault(await r.json().catch(() => null));
|
||
this.d.log?.("ошибка API QuickBooks", { status: r.status, path: shortPath, intuit_tid: tid, attempt, faultType: fault.type, code: fault.code, message: fault.message });
|
||
if (r.status === 401 && !force) { force = true; continue; }
|
||
if (r.status === 429 || r.status >= 500) { await sleep(2000 * (attempt + 1)); continue; }
|
||
throw new QboApiError(
|
||
`QuickBooks ${r.status} на ${shortPath}${fault.code ? ` code=${fault.code}` : ""}${fault.message ? ` ${fault.message}` : ""}${tid ? ` intuit_tid=${tid}` : ""}`,
|
||
r.status, fault.type, fault.code, fault.detail, tid,
|
||
);
|
||
}
|
||
throw new QboApiError(`QuickBooks: не удалось выполнить ${shortPath} за ${attempts} попыток`, 0);
|
||
}
|
||
}
|