UNPKG

lesca-fetcher

Version:

integrate fetch for easier use

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