UNPKG

qsu

Version:

qsu is a utility library that contains useful and frequently used functions. Start with your preferred language and the modern development environment.

1 lines 2.45 kB
import{objToQueryString as t}from"../../object/objToQueryString.js";import{urlJoin as e}from"../../string/urlJoin.js";import{Readable as r}from"node:stream";function a(t){let e;if(t?.headers?.["Content-Type"])e=t?.headers?.["Content-Type"];else switch(t?.bodyType){case"form-data":e="multipart/form-data";break;case"x-www-form-urlencoded":e="application/x-www-form-urlencoded";break;case"json":e="application/json;charset=UTF-8";break;case"text":e="plain/text;charset=UTF-8";break;default:e=null}const r={};return t?.auth?.bearer&&t?.auth?.bearer.length>0&&(r.Authorization=`Bearer ${t?.auth?.bearer}`),t?.auth?.apiKey&&t?.auth?.apiKey.length>0&&(r["x-API-key"]=t?.auth?.apiKey),{...r,...e?{"Content-Type":e}:{},"Accept-Encoding":"gzip, deflate, br",Charset:"utf-8",...t?.headers}}export async function fetchData(o,i){const n=i||{},s=n.queryParameters?`?${t(n.queryParameters)}`:null;let h,l,u=null;if(o.length<1)throw new Error("`url` is required");if(n.body)switch(n.bodyType){case"x-www-form-urlencoded":u=t(n.body);break;case"form-data":u=n.body;break;default:u=JSON.stringify(n.body)}if(n.method&&(n.get||n.post||n.put||n.delete||n.patch))throw new Error("`method` and `get|post|put|delete|patch` cannot be used together");if(h=n.get?"GET":n.post?"POST":n.put?"PUT":n.delete?"DELETE":n.patch?"PATCH":n.method||"GET",!n.host&&!o.startsWith("/"))throw new Error("`url` must begin with `/`.");if(n.host&&n.host.length>0){if(o.startsWith("http")||o.includes("://"))throw new Error("If `host` is specified, `url` must begin with `/`.");l=e(n.host,o)}else l=o;try{const t=await fetch(e(l,s),{...n.auth?{credentials:"include"}:{},...n.timeout?{signal:AbortSignal.timeout(n.timeout)}:{},method:h,body:u,headers:a(n)});if(!t.ok||!t.body)return null;const o=t.headers.get("content-type")||"",i=function(t,e){if(/attachment|filename=/i.test(e))return!0;const r=t.split(";")?.[0]?.trim()?.toLowerCase()||"";return!["text/html","text/css","text/javascript","application/json","application/ld+json","application/xml","text/xml","text/plain"].some(t=>r===t)&&!r.startsWith("text/")&&(r.startsWith("application/")||r.startsWith("image/")||r.startsWith("video/")||r.startsWith("audio/")||r.startsWith("font/"))}(o,t.headers.get("content-disposition")||"");return n.toStream?r.fromWeb(t.body):i?Buffer.from(await t.arrayBuffer()):o.length<1?await t.text():o.includes("application/json")?await t.json():await t.text()}catch(t){return n.onError&&n.onError(t),null}}