fetch-request-browser
Advanced tools
Comparing version 1.0.6 to 1.0.7
@@ -17,3 +17,3 @@ import { IRequestInput, IRequestMethod, IRequestOptions, IResponseDataType, IOptions, IRequestResponse } from './shared/types.js'; | ||
*/ | ||
declare const send: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const send: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
/** | ||
@@ -37,3 +37,3 @@ * Builds and sends a GET HTTP Request based on the provided input and options. | ||
*/ | ||
declare const sendGET: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const sendGET: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
/** | ||
@@ -54,3 +54,3 @@ * Builds and sends a POST HTTP Request based on the provided input and options. | ||
*/ | ||
declare const sendPOST: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const sendPOST: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
/** | ||
@@ -71,3 +71,3 @@ * Builds and sends a PUT HTTP Request based on the provided input and options. | ||
*/ | ||
declare const sendPUT: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const sendPUT: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
/** | ||
@@ -88,3 +88,3 @@ * Builds and sends a PATCH HTTP Request based on the provided input and options. | ||
*/ | ||
declare const sendPATCH: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const sendPATCH: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
/** | ||
@@ -105,3 +105,3 @@ * Builds and sends a DELETE HTTP Request based on the provided input and options. | ||
*/ | ||
declare const sendDELETE: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
declare const sendDELETE: <T>(input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse<T>>; | ||
export { type IRequestInput, type IRequestMethod, type IRequestOptions, type IResponseDataType, type IOptions, type IRequestResponse, send, sendGET, sendPOST, sendPUT, sendPATCH, sendDELETE, }; |
@@ -1,1 +0,1 @@ | ||
import{extractMessage}from"error-message-utils";import{isArrayValid,delay}from"web-utils-kit";import{buildOptions,buildRequest,extractResponseData}from"./utils/utils.js";import{validateResponse}from"./validations/validations.js";const __executeSend=async(e,s)=>{const t=buildOptions(s),n=buildRequest(e,t.requestOptions),r=await fetch(n);return validateResponse(n,r,t),r.redirected&&console.warn(`The request sent to '${n.url}' was redirected. Please update the implementation to avoid future redirections.`),{code:r.status,headers:r.headers,data:await extractResponseData(r,t.responseDataType)}},send=async(e,s,t)=>{try{return await __executeSend(e,s)}catch(n){if(extractMessage(n).includes("429")||!isArrayValid(t))throw n;return await delay(t[0]),send(e,s,t.slice(1))}},sendGET=async(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"GET"}},t),sendPOST=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"POST"}},t),sendPUT=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"PUT"}},t),sendPATCH=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"PATCH"}},t),sendDELETE=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"DELETE"}},t);export{send,sendGET,sendPOST,sendPUT,sendPATCH,sendDELETE}; | ||
import{extractMessage}from"error-message-utils";import{isArrayValid,delay}from"web-utils-kit";import{buildOptions,buildRequest,extractResponseData}from"./utils/utils.js";import{validateResponse}from"./validations/validations.js";const __executeSend=async(e,s)=>{const t=buildOptions(s),n=buildRequest(e,t.requestOptions),r=await fetch(n);return validateResponse(n,r,t),r.redirected&&console.warn(`The request sent to '${n.url}' was redirected. Please update the implementation to avoid future redirections.`),{code:r.status,headers:r.headers,data:await extractResponseData(r,t.responseDataType)}},send=async(e,s,t)=>{try{return await __executeSend(e,s)}catch(n){if(extractMessage(n).includes("429")||!isArrayValid(t))throw n;return await delay(t[0]),send(e,s,t.slice(1))}},sendGET=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"GET"}},t),sendPOST=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"POST"}},t),sendPUT=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"PUT"}},t),sendPATCH=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"PATCH"}},t),sendDELETE=(e,s,t)=>send(e,{...s,requestOptions:{...s?.requestOptions,method:"DELETE"}},t);export{send,sendGET,sendPOST,sendPUT,sendPATCH,sendDELETE}; |
@@ -11,8 +11,11 @@ /** | ||
* does not accept plain objects. Even though this makes sense, the body is processed in the | ||
* utilities so the Request's body is always instantiated with a string. | ||
* utilities so the Request's body is always going to have a valid type. | ||
*/ | ||
interface IRequestOptions extends RequestInit { | ||
interface IRequestOptions extends Omit<RequestInit, 'body'> { | ||
method: IRequestMethod; | ||
body: any; | ||
body: BodyInit | Record<string, unknown> | Array<unknown> | null; | ||
} | ||
interface IProcessedRequestOptions extends RequestInit { | ||
method: IRequestMethod; | ||
} | ||
/** | ||
@@ -33,3 +36,2 @@ * Request Method | ||
*/ | ||
type IResponseData<T> = T extends 'arrayBuffer' ? ArrayBuffer : T extends 'blob' ? Blob : T extends 'formData' ? FormData : T extends 'json' ? any : T extends 'text' ? string : never; | ||
/** | ||
@@ -59,7 +61,7 @@ * Options | ||
*/ | ||
interface IRequestResponse { | ||
interface IRequestResponse<T> { | ||
code: number; | ||
headers: Headers; | ||
data: any; | ||
data: T; | ||
} | ||
export type { IRequestInput, IRequestOptions, IRequestMethod, IResponseDataType, IResponseData, IOptions, IRequestResponse, }; | ||
export type { IRequestInput, IRequestOptions, IProcessedRequestOptions, IRequestMethod, IResponseDataType, IOptions, IRequestResponse, }; |
@@ -1,2 +0,2 @@ | ||
import { IRequestInput, IResponseDataType, IResponseData, IRequestOptions, IOptions } from '../shared/types.js'; | ||
import { IRequestInput, IRequestOptions, IResponseDataType, IOptions } from '../shared/types.js'; | ||
/** | ||
@@ -21,3 +21,3 @@ * Builds the Request Instance based on given input and options. | ||
*/ | ||
declare const extractResponseData: <T extends IResponseDataType>(res: Response, dType: T) => Promise<IResponseData<T>>; | ||
declare const extractResponseData: <T>(res: Response, dType: IResponseDataType) => Promise<T>; | ||
/** | ||
@@ -24,0 +24,0 @@ * Builds the main options object based on given args (if any). |
@@ -1,1 +0,1 @@ | ||
import{encodeError,isEncodedError}from"error-message-utils";import{ERRORS}from"../shared/errors.js";const __buildRequestInput=e=>{if(e instanceof URL)return e;try{return new URL(e)}catch(e){throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_URL))}},__buildRequestHeaders=(e,r)=>{let t;if(e&&"object"==typeof e)try{t=new Headers(e)}catch(e){throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_HEADERS))}else t=e instanceof Headers?e:"GET"===r?new Headers({Accept:"application/json"}):new Headers({Accept:"application/json","Content-Type":"application/json"});return t.has("Accept")||t.append("Accept","application/json"),t.has("Content-Type")||"GET"===r||t.append("Content-Type","application/json"),t},__buildRequestBody=e=>e?"object"==typeof e?JSON.stringify(e):e:null,__buildRequestOptions=(e={})=>{const r=e.method??"GET";return{method:r,mode:e.mode??"cors",cache:e.cache??"default",credentials:e.credentials??"same-origin",headers:__buildRequestHeaders(e.headers,r),priority:e.priority??"auto",redirect:e.redirect??"follow",referrer:e.referrer??"about:client",referrerPolicy:e.referrerPolicy??"no-referrer-when-downgrade",signal:e.signal,integrity:e.integrity||"",keepalive:e.keepalive??!1,body:"GET"===r?null:__buildRequestBody(e.body)}},buildRequest=(e,r)=>{try{return new Request(__buildRequestInput(e),__buildRequestOptions(r))}catch(e){if(isEncodedError(e))throw e;throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_OPTIONS))}},extractResponseData=async(e,r)=>{switch(r){case"arrayBuffer":return e.arrayBuffer();case"blob":return e.blob();case"formData":return e.formData();case"json":return e.json();case"text":return e.text();default:throw new Error(encodeError(`The provided response data type '${r}' is invalid.`,ERRORS.INVALID_RESPONSE_DTYPE))}},buildOptions=(e={})=>({requestOptions:e.requestOptions,responseDataType:e.responseDataType??"json",acceptableStatusCodes:e.acceptableStatusCodes,acceptableStatusCodesRange:e.acceptableStatusCodesRange??{min:200,max:299},skipStatusCodeValidation:e.skipStatusCodeValidation??!1});export{buildRequest,extractResponseData,buildOptions}; | ||
import{encodeError,isEncodedError}from"error-message-utils";import{isArrayValid,isObjectValid}from"web-utils-kit";import{ERRORS}from"../shared/errors.js";const __buildRequestInput=e=>{if(e instanceof URL)return e;try{return new URL(e)}catch(e){throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_URL))}},__buildRequestHeaders=(e,r)=>{let t;if(e&&"object"==typeof e)try{t=new Headers(e)}catch(e){throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_HEADERS))}else t=e instanceof Headers?e:"GET"===r?new Headers({Accept:"application/json"}):new Headers({Accept:"application/json","Content-Type":"application/json"});return t.has("Accept")||t.append("Accept","application/json"),t.has("Content-Type")||"GET"===r||t.append("Content-Type","application/json"),t},__buildRequestBody=e=>e?isObjectValid(e,!0)||isArrayValid(e,!0)?JSON.stringify(e):e:null,__buildRequestOptions=(e={})=>{const r=e.method??"GET";return{method:r,mode:e.mode??"cors",cache:e.cache??"default",credentials:e.credentials??"same-origin",headers:__buildRequestHeaders(e.headers,r),priority:e.priority??"auto",redirect:e.redirect??"follow",referrer:e.referrer??"about:client",referrerPolicy:e.referrerPolicy??"no-referrer-when-downgrade",signal:e.signal,integrity:e.integrity||"",keepalive:e.keepalive??!1,body:"GET"===r?null:__buildRequestBody(e.body)}},buildRequest=(e,r)=>{try{return new Request(__buildRequestInput(e),__buildRequestOptions(r))}catch(e){if(isEncodedError(e))throw e;throw new Error(encodeError(e,ERRORS.INVALID_REQUEST_OPTIONS))}},extractResponseData=async(e,r)=>{switch(r){case"arrayBuffer":return e.arrayBuffer();case"blob":return e.blob();case"formData":return e.formData();case"json":return e.json();case"text":return e.text();default:throw new Error(encodeError(`The provided response data type '${r}' is invalid.`,ERRORS.INVALID_RESPONSE_DTYPE))}},buildOptions=(e={})=>({requestOptions:e.requestOptions,responseDataType:e.responseDataType??"json",acceptableStatusCodes:e.acceptableStatusCodes,acceptableStatusCodesRange:e.acceptableStatusCodesRange??{min:200,max:299},skipStatusCodeValidation:e.skipStatusCodeValidation??!1});export{buildRequest,extractResponseData,buildOptions}; |
{ | ||
"name": "fetch-request-browser", | ||
"version": "1.0.6", | ||
"version": "1.0.7", | ||
"description": "The fetch-request-browser package makes working with external APIs simple and efficient. This intuitive wrapper leverages the power of the Fetch API, providing a clean and concise interface for your API interactions.", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
@@ -25,3 +25,3 @@ # Fetch Request Browser | ||
await sendGET( | ||
await sendGET<IHTTPBinResponse>( | ||
'https://httpbin.org/get?someUid=5', | ||
@@ -69,3 +69,3 @@ { | ||
await sendPOST( | ||
await sendPOST<IHTTPBinResponse>( | ||
'https://httpbin.org/post?id=1', | ||
@@ -131,3 +131,3 @@ { | ||
```typescript | ||
await send( | ||
await send<IHTTPBinResponse>( | ||
'https://httpbin.org/get?foo=hey&bar=123', { | ||
@@ -171,3 +171,3 @@ requestOptions: { method: 'GET' } | ||
```typescript | ||
await sendGET('https://httpbin.org/get?foo=hey&bar=123'); | ||
await sendGET<IHTTPBinResponse>('https://httpbin.org/get?foo=hey&bar=123'); | ||
// { | ||
@@ -207,3 +207,3 @@ // code: 200, | ||
```typescript | ||
await sendPOST( | ||
await sendPOST<IHTTPBinResponse>( | ||
'https://httpbin.org/post', | ||
@@ -259,3 +259,3 @@ { | ||
```typescript | ||
await sendPUT( | ||
await sendPUT<IHTTPBinResponse>( | ||
'https://httpbin.org/put', | ||
@@ -311,3 +311,3 @@ { | ||
```typescript | ||
await sendPATCH( | ||
await sendPATCH<IHTTPBinResponse>( | ||
'https://httpbin.org/patch', | ||
@@ -363,3 +363,3 @@ { | ||
```typescript | ||
await sendDELETE('https://httpbin.org/delete?id=1'); | ||
await sendDELETE<IHTTPBinResponse>('https://httpbin.org/delete?id=1'); | ||
// { | ||
@@ -427,11 +427,2 @@ // code: 200, | ||
<details> | ||
<summary><code>IRequestMethod</code></summary> | ||
The HTTP Methods supported by this library. To make use of a different one, pass the method name directly in the request options. | ||
```typescript | ||
type IRequestMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; | ||
``` | ||
</details> | ||
<details> | ||
<summary><code>RequestInit</code></summary> | ||
@@ -477,8 +468,12 @@ | ||
The options that can be applied when sending a Fetch Request. | ||
IMPORTANT: the reason RequestInit is extended is because in the original type, the body property does not accept plain objects. Even though this makes sense, utilities so the Request's body is always instantiated with a string. | ||
IMPORTANT: the reason RequestInit is extended is because in the original type, the body property does not accept plain objects. Even though this makes sense, utilities so the Request's body is always going to have a valid type. | ||
```typescript | ||
interface IRequestOptions extends RequestInit { | ||
interface IRequestOptions extends Omit<RequestInit, 'body'> { | ||
method: IRequestMethod; // this lib only makes use of these methods | ||
body: any; | ||
body: BodyInit | Record<string, unknown> | Array<unknown> | null; | ||
} | ||
interface IProcessedRequestOptions extends RequestInit { | ||
method: IRequestMethod; | ||
} | ||
``` | ||
@@ -528,7 +523,7 @@ </details> | ||
<details> | ||
<summary><code>IRequestResponse</code></summary> | ||
<summary><code>IRequestResponse<T></code></summary> | ||
The object containing the result of the Request. | ||
```typescript | ||
interface IRequestResponse { | ||
interface IRequestResponse<T> { | ||
// the HTTP status code extracted from the Response | ||
@@ -541,3 +536,3 @@ code: number; | ||
// the data extracted from the Response Instance | ||
data: any; | ||
data: T; | ||
} | ||
@@ -544,0 +539,0 @@ ``` |
34872
211
588