UNPKG

ai-utils.js

Version:

Build AI applications, chatbots, and agents with JavaScript and TypeScript.

97 lines (96 loc) 3.17 kB
import { ApiCallError } from "./ApiCallError.js"; export const createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => { const parsedResult = responseSchema.safeParse(await response.json()); if (!parsedResult.success) { throw new ApiCallError({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, url, requestBodyValues, }); } return parsedResult.data; }; export const createTextResponseHandler = () => async ({ response }) => response.text(); export const postJsonToApi = async ({ url, apiKey, body, failedResponseHandler, successfulResponseHandler, abortSignal, }) => postToApi({ url, apiKey, contentType: "application/json", body: { content: JSON.stringify(body), values: body, }, failedResponseHandler, successfulResponseHandler, abortSignal, }); export const postToApi = async ({ url, apiKey, contentType, body, successfulResponseHandler, failedResponseHandler, abortSignal, }) => { try { const headers = {}; if (apiKey !== undefined) { headers["Authorization"] = `Bearer ${apiKey}`; } if (contentType !== null) { headers["Content-Type"] = contentType; } const response = await fetch(url, { method: "POST", headers, body: body.content, signal: abortSignal, }); if (!response.ok) { try { throw await failedResponseHandler({ response, url, requestBodyValues: body.values, }); } catch (error) { if (error instanceof Error) { if (error.name === "AbortError" || error instanceof ApiCallError) { throw error; } } throw new ApiCallError({ message: "Failed to process error response", cause: error, statusCode: response.status, url, requestBodyValues: body.values, }); } } try { return await successfulResponseHandler({ response, url, requestBodyValues: body.values, }); } catch (error) { if (error instanceof Error) { if (error.name === "AbortError" || error instanceof ApiCallError) { throw error; } } throw new ApiCallError({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, requestBodyValues: body.values, }); } } catch (error) { if (error instanceof Error) { if (error.name === "AbortError") { throw error; } } throw error; } };