UNPKG

siliconflow-serverless-client

Version:

![@siliconflow/siliconflow-js npm package](https://img.shields.io/npm/v/@siliconflow/siliconflow-js?color=%25237527D7&label=@siliconflow/siliconflow-js&style=flat-square)

56 lines (51 loc) 1.52 kB
import { getConfig } from "./config"; import { getUserAgent, isBrowser } from "./runtime"; const isCloudflareWorkers = typeof navigator !== "undefined" && navigator?.userAgent === "Cloudflare-Workers"; export async function dispatchRequest<Input, Output>( method: string, targetUrl: string, input: Input, ): Promise<Output> { const { credentials: credentialsValue, requestMiddleware, responseHandler, } = getConfig(); const userAgent = isBrowser() ? {} : { "User-Agent": getUserAgent() }; const credentials = typeof credentialsValue === "function" ? credentialsValue() : credentialsValue; const { url, headers } = await requestMiddleware({ url: targetUrl, }); // console.log("[headers]", headers); const authHeader = credentials ? { Authorization: `Bearer ${credentials}` } : {}; if (typeof window !== "undefined" && credentials) { console.warn( "The siliconflow credentials are exposed in the browser's environment. " + "That's not recommended for production use cases.", ); } const requestHeaders = { ...authHeader, Accept: "application/json", "Content-Type": "application/json", ...userAgent, ...(headers ?? {}), } as HeadersInit; const response = await fetch(url, { method, headers: requestHeaders, ...(!isCloudflareWorkers && { mode: "cors" }), body: method.toLowerCase() !== "get" && input ? JSON.stringify(input) : undefined, }); return await responseHandler(response); }