grab-url
Version:
📥 Generate Request to API from Browser
3 lines (2 loc) • 7.28 kB
JavaScript
import{log as e,printJSONStructure as t}from"./log.es.js";async function o(r,a){var{headers:s,response:l={},method:d=(a?.post?"POST":a?.put?"PUT":a?.patch?"PATCH":"GET"),cache:c=!1,cacheForTime:u=60,timeout:f=30,baseURL:p="undefined"!=typeof process&&process.env.SERVER_API_URL||"/api/",cancelOngoingIfNew:g=!1,cancelNewIfOngoing:m=!1,rateLimit:y=0,debug:b=!1,infiniteScroll:w=null,setDefaults:h=!1,retryAttempts:v=0,logger:T=e,onRequest:L=null,onResponse:S=null,onError:E=null,onStream:x=null,repeatEvery:O=null,repeat:k=0,debounce:P=0,regrabOnStale:j=!1,regrabOnFocus:D=!1,regrabOnNetwork:N=!1,post:q=!1,put:A=!1,patch:F=!1,body:R=null,...$}={..."undefined"!=typeof window?window?.grab?.defaults:globalThis?.grab?.defaults||{},...a};let I=e=>r.startsWith(e);I("http:")||I("https:")?p="":I("/")||p.endsWith("/")?I("/")&&p.endsWith("/")&&(r=r.slice(1)):r="/"+r;try{if(P>0)return await n(async()=>{await o(r,{...a,debounce:0})},1e3*P);if(k>1){for(let e=0;e<k;e++)await o(r,{...a,repeat:0});return l}if(O)return setInterval(async()=>{await o(r,{...a,repeat:0,repeatEvery:null})},1e3*O),l;if(a?.setDefaults)return void("undefined"!=typeof window?window.grab.defaults={...a,setDefaults:void 0}:void 0!==globalThis.grab&&(globalThis.grab.defaults={...a,setDefaults:void 0}));if("undefined"!=typeof window){const e=async()=>await o(r,{...a,cache:!1});j&&c&&setTimeout(e,1e3*u),N&&window.addEventListener("online",e),D&&(window.addEventListener("focus",e),document.addEventListener("visibilitychange",async()=>{"visible"===document.visibilityState&&await e()}))}let i="function"==typeof l?l:null;l&&!i||(l={});var[J,H,C]=w||[];if(w?.length&&void 0!==C&&"undefined"!=typeof window){let t="string"==typeof C?document.querySelector(C):C;t?window.scrollListener&&void 0!==t&&"function"==typeof t.removeEventListener&&t.removeEventListener("scroll",window.scrollListener):e("paginateDOM not found",{color:"red"}),window.scrollListener=async e=>{const t=e.target;localStorage.setItem("scroll",JSON.stringify([t.scrollTop,t.scrollLeft,C])),t.scrollHeight-t.scrollTop<=t.clientHeight+200&&await o(r,{...a,cache:!1,[J]:v?.currentPage+1})},t&&t.addEventListener("scroll",window.scrollListener)}let h=JSON.stringify(J?{...$,[J]:void 0}:$),v=o?.log?.find(e=>e.request==h&&e.path==r);if(J){let e=v?.currentPage+1||$?.[J]||1;v||(l[H]=[],e=1),v&&(v.currentPage=e),$={...$,[J]:e}}else{for(let e of Object.keys(l))l[e]=void 0;if(c&&(!u||v?.lastFetchTime>Date.now()-1e3*u)){for(let e of Object.keys(v.res))l[e]=v.res[e];i&&(l=i(l))}}if(i?i({isLoading:!0}):"object"==typeof l&&(l.isLoading=!0),i&&(l=i(l)),y>0&&v?.lastFetchTime&&v.lastFetchTime>Date.now()-1e3*y)throw new Error(`Fetch rate limit exceeded for ${r}. \n Wait ${y}s between requests.`);if(v?.controller)if(g)v.controller.abort();else if(m)return{isLoading:!0};void 0!==o.log&&o.log?.unshift({path:r,request:h,lastFetchTime:Date.now(),controller:new AbortController});let E={method:d,headers:{"Content-Type":"application/json",Accept:"application/json",...s},body:$.body,redirect:"follow",cache:c?"force-cache":"no-store",signal:g?o.log[0]?.controller?.signal:AbortSignal.timeout(1e3*f)},q="";["POST","PUT","PATCH"].includes(d)?E.body=$.body||JSON.stringify($):q=(Object.keys($).length?"?":"")+new URLSearchParams($).toString(),"function"==typeof L&&([r,l,$,E]=L(r,l,$,E));let A=null,F=/* @__PURE__ */new Date,R=o.mock?.[r],I=e=>new Promise(t=>setTimeout(t,1e3*e||0));if(!R||R.params&&R.method!=d||R.params&&h!=JSON.stringify(R.params)){if(A=await fetch(p+r+q,E).catch(e=>{throw new Error(e.message)}),!A.ok)throw new Error(`HTTP error: ${A.status} ${A.statusText}`);let e=A.headers.get("content-type");x?await x(A.body):A=await(e?e.includes("application/json")?A&&A.json():e.includes("application/pdf")||e.includes("application/octet-stream")?A.blob():A.text():A.json()).catch(e=>{throw new Error("Error parsing response: "+e)})}else await I(R.delay),A="function"==typeof R.response?R.response($):R.response;"function"==typeof S&&([r,l,$,E]=S(r,l,$,E)),i?i({isLoading:void 0}):"object"==typeof l&&delete l?.isLoading,delete v?.controller;const U=((Number(/* @__PURE__ */new Date)-Number(F))/1e3).toFixed(1);if(b&&T("Path:"+p+r+q+"\n"+JSON.stringify(a,null,2)+"\nTime: "+U+"s\nResponse: "+t(A)),"object"==typeof A){for(let e of Object.keys(A))l[e]=H==e&&l[e]?.length?[...l[e],...A[e]]:A[e];void 0!==l&&(l.data=A)}else i?i({data:A,...A}):"object"==typeof l&&(l.data=A);return void 0!==o.log&&o.log?.unshift({path:r,request:JSON.stringify({...$,paginateKey:void 0}),response:l,lastFetchTime:Date.now()}),i&&(l=i(l)),l}catch(U){let e="Error: "+U.message+"\nPath:"+p+r+"\n";return void 0===l&&(l={}),"function"==typeof E&&E(U.message,p+r,$),a?.retryAttempts>0?await o(r,{...a,retryAttempts:--a.retryAttempts}):(!U.message.includes("signal")&&a?.debug&&(T(e,{color:"red"}),b&&"undefined"!=typeof document&&i(e)),l.error=U.message,"function"==typeof l?(l.data=l({isLoading:void 0,error:U.message}),l=l.data):delete l?.isLoading,void 0!==o.log&&o.log?.unshift({path:r,request:JSON.stringify($),error:U.message}),l)}}o.instance=(e={})=>(t,n={})=>o(t,{...e,...n});const n=async(e,t)=>{let o;return async function(...n){clearTimeout(o),o=setTimeout(async()=>{clearTimeout(o),await e(...n)},t)}};function i(e){if("undefined"==typeof document)return;let t,o=document.getElementById("alert-overlay");o||(o=document.body.appendChild(document.createElement("div")),o.id="alert-overlay",o.setAttribute("style","position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center"),o.innerHTML='<div id="alert-box" style="background:#fff;padding:1.5em 2em;border-radius:8px;box-shadow:0 2px 16px #0003;min-width:220px;max-height:80vh;position:relative;display:flex;flex-direction:column;">\n <button id="close-alert" style="position:absolute;top:12px;right:20px;font-size:1.5em;background:none;border:none;cursor:pointer;color:black;">×</button>\n <div id="alert-list" style="overflow:auto;flex:1;"></div>\n </div>',o.addEventListener("click",e=>e.target==o&&o.remove()),document.getElementById("close-alert").onclick=()=>o.remove()),t=o.querySelector("#alert-list"),t.innerHTML+=`<div style="border-bottom:1px solid #333; font-size:1.2em;margin:0.5em 0;">${e}</div>`}function r(){document.addEventListener("keydown",e=>{if("i"===e.key&&e.ctrlKey&&e.altKey){let e=" ";for(let n of o.log)e+=`<div style="margin-bottom:1em; border-bottom:1px solid #ccc; padding-bottom:1em;">\n <b>Path:</b> ${n.path}<br>\n <b>Request:</b> ${t(n.request,0,"html")}<br>\n <b>Response:</b> ${t(n.response,0,"html")}<br> \n <b>Time:</b> ${new Date(n.lastFetchTime).toLocaleString()}\n </div>`;i(e)}})}"undefined"!=typeof window?(window.log=e,window.grab=o,window.grab.log=[],window.grab.mock={},window.grab.defaults={},r(),document.addEventListener("DOMContentLoaded",()=>{let[e,t,o]=JSON.parse(localStorage.getItem("scroll"))||[];e&&(document.querySelector(o).scrollTop=e,document.querySelector(o).scrollLeft=t)})):"undefined"!=typeof globalThis&&(o.log=[],o.mock={},o.defaults={},globalThis.log=e,globalThis.grab=o.instance());export{o as default,o as grab,e as log,t as printJSONStructure,r as setupDevTools,i as showAlert};
//# sourceMappingURL=grab-api.es.js.map