UNPKG

lesca-fetcher

Version:

integrate fetch for easier use

2 lines (1 loc) 1.79 kB
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var m=(t=>(t.URL_ENCODED="application/x-www-form-urlencoded; charset=UTF-8",t.JSON="application/json;charset=utf-8",t))(m||{}),p=(t=>(t[t.string=0]="string",t[t.JSON=1]="JSON",t))(p||{});const w={hostUrl:"https://jsonplaceholder.typicode.com/todos/1",contentType:"application/json;charset=utf-8",formatType:1};let d,h,f;const T=t=>{const i={...w,...t},{hostUrl:o,contentType:s,formatType:n}=i;d=o.slice(-1)==="/"?o.slice(0,-1):o,f=n,h=new Headers({"Content-Type":s})},g=t=>{h.set("Authorization",`Bearer ${t}`)},y=t=>{Object.entries(t).forEach(([i,o])=>{h.set(i,o)})},l=(t="/api")=>t.slice(0,1)==="/"?`${d}${t}`:`${d}/${t}`,O=(t="/api",i,o)=>{const s="POST";let n=JSON.stringify(i);return h.get("Content-Type")==="application/x-www-form-urlencoded; charset=UTF-8"&&(n=Object.entries(i).map(e=>`${e[0]}=${e[1]}`).join("&")),o?new Promise((e,a)=>{const r={...o,Authorization:`Bearer ${h.get("Authorization")}`};fetch(l(t),{method:s,body:n,headers:new Headers(r)}).then(c=>{c.json().then(u=>e(u)).catch(u=>a(u))}).catch(c=>a(c))}):f===1?new Promise((e,a)=>{fetch(l(t),{method:s,body:n,headers:h}).then(r=>{r.json().then(c=>e(c)).catch(c=>a(c))}).catch(r=>a(r))}):new Promise((e,a)=>{fetch(l(t),{method:s,body:n,headers:h}).then(r=>{r.text().then(c=>e(c)).catch(c=>a(c))}).catch(r=>a(r))})},P=(t="/api")=>f===1?new Promise((o,s)=>{fetch(l(t),{method:"GET",headers:h}).then(n=>{n.json().then(e=>o(e)).catch(e=>s(e))}).catch(n=>s(n))}):new Promise((o,s)=>{fetch(l(t),{method:"GET",headers:h}).then(n=>{n.text().then(e=>o(e)).catch(e=>s(e))}).catch(n=>s(n))}),$={install:T,post:O,get:P,setJWT:g,setHeader:y};exports.contentType=m;exports.default=$;exports.formatType=p;exports.mergePath=l;