fetch-request-browser
Advanced tools
Comparing version 1.0.5 to 1.0.6
@@ -101,2 +101,2 @@ import { IRequestInput, IRequestMethod, IRequestOptions, IResponseDataType, IOptions, IRequestResponse } from './shared/types.js'; | ||
declare const sendDELETE: (input: IRequestInput, options?: Partial<IOptions>, retryDelaySchedule?: number[]) => Promise<IRequestResponse>; | ||
export { IRequestInput, IRequestMethod, IRequestOptions, IResponseDataType, IOptions, IRequestResponse, send, sendGET, sendPOST, sendPUT, sendPATCH, sendDELETE, }; | ||
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{buildOptions,buildRequest,extractResponseData,delay}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")||!Array.isArray(t)||0===t.length)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=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}; |
@@ -1,10 +0,5 @@ | ||
declare enum ERRORS { | ||
INVALID_REQUEST_URL = "INVALID_REQUEST_URL", | ||
INVALID_REQUEST_HEADERS = "INVALID_REQUEST_HEADERS", | ||
INVALID_REQUEST_OPTIONS = "INVALID_REQUEST_OPTIONS", | ||
INVALID_RESPONSE_DTYPE = "INVALID_RESPONSE_DTYPE", | ||
UNEXPECTED_RESPONSE_STATUS_CODE = "UNEXPECTED_RESPONSE_STATUS_CODE", | ||
INVALID_RESPONSE_CONTENT_TYPE = "INVALID_RESPONSE_CONTENT_TYPE", | ||
CONTENT_TYPE_MISSMATCH = "CONTENT_TYPE_MISSMATCH" | ||
} | ||
type IErrorCode = 'INVALID_REQUEST_URL' | 'INVALID_REQUEST_HEADERS' | 'INVALID_REQUEST_OPTIONS' | 'INVALID_RESPONSE_DTYPE' | 'UNEXPECTED_RESPONSE_STATUS_CODE' | 'INVALID_RESPONSE_CONTENT_TYPE' | 'CONTENT_TYPE_MISSMATCH'; | ||
declare const ERRORS: { | ||
[key in IErrorCode]: IErrorCode; | ||
}; | ||
export { ERRORS, }; |
@@ -1,1 +0,1 @@ | ||
var ERRORS;!function(E){E.INVALID_REQUEST_URL="INVALID_REQUEST_URL",E.INVALID_REQUEST_HEADERS="INVALID_REQUEST_HEADERS",E.INVALID_REQUEST_OPTIONS="INVALID_REQUEST_OPTIONS",E.INVALID_RESPONSE_DTYPE="INVALID_RESPONSE_DTYPE",E.UNEXPECTED_RESPONSE_STATUS_CODE="UNEXPECTED_RESPONSE_STATUS_CODE",E.INVALID_RESPONSE_CONTENT_TYPE="INVALID_RESPONSE_CONTENT_TYPE",E.CONTENT_TYPE_MISSMATCH="CONTENT_TYPE_MISSMATCH"}(ERRORS||(ERRORS={}));export{ERRORS}; | ||
const ERRORS={INVALID_REQUEST_URL:"INVALID_REQUEST_URL",INVALID_REQUEST_HEADERS:"INVALID_REQUEST_HEADERS",INVALID_REQUEST_OPTIONS:"INVALID_REQUEST_OPTIONS",INVALID_RESPONSE_DTYPE:"INVALID_RESPONSE_DTYPE",UNEXPECTED_RESPONSE_STATUS_CODE:"UNEXPECTED_RESPONSE_STATUS_CODE",INVALID_RESPONSE_CONTENT_TYPE:"INVALID_RESPONSE_CONTENT_TYPE",CONTENT_TYPE_MISSMATCH:"CONTENT_TYPE_MISSMATCH"};export{ERRORS}; |
@@ -28,8 +28,2 @@ import { IRequestInput, IResponseDataType, IResponseData, IRequestOptions, IOptions } from '../shared/types.js'; | ||
declare const buildOptions: (options?: Partial<IOptions>) => IOptions; | ||
/** | ||
* Creates an asynchronous delay that resolves once the provided seconds have passed. | ||
* @param seconds | ||
* @returns Promise<void> | ||
*/ | ||
declare const delay: (seconds: number) => Promise<void>; | ||
export { buildRequest, extractResponseData, buildOptions, delay, }; | ||
export { buildRequest, extractResponseData, buildOptions, }; |
@@ -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}),delay=e=>new Promise((r=>{setTimeout(r,1e3*e)}));export{buildRequest,extractResponseData,buildOptions,delay}; | ||
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}; |
{ | ||
"name": "fetch-request-browser", | ||
"version": "1.0.5", | ||
"version": "1.0.6", | ||
"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.", | ||
@@ -36,13 +36,14 @@ "main": "dist/index.js", | ||
"devDependencies": { | ||
"@types/node": "^20.14.12", | ||
"@typescript-eslint/eslint-plugin": "^7.17.0", | ||
"@typescript-eslint/parser": "^7.17.0", | ||
"@types/node": "^20.17.9", | ||
"@typescript-eslint/eslint-plugin": "^7.18.0", | ||
"@typescript-eslint/parser": "^7.18.0", | ||
"eslint-config-airbnb-typescript": "^18.0.0", | ||
"ts-lib-builder": "^1.0.3", | ||
"typescript": "^5.5.4", | ||
"ts-lib-builder": "^1.0.5", | ||
"typescript": "^5.7.2", | ||
"vitest": "^1.6.0" | ||
}, | ||
"dependencies": { | ||
"error-message-utils": "^1.1.1" | ||
"error-message-utils": "^1.1.2", | ||
"web-utils-kit": "^1.0.3" | ||
} | ||
} |
562
README.md
@@ -15,22 +15,19 @@ # Fetch Request Browser | ||
```bash | ||
$ npm install -S fetch-request-browser | ||
npm install -S fetch-request-browser | ||
``` | ||
### Examples | ||
Send a `GET` request that will retry (up to 3 times) on failure to [HTTPBin](https://httpbin.org/): | ||
<br /> | ||
## Usage | ||
```typescript | ||
import { send } from 'fetch-request-browser'; | ||
import { sendGET } from 'fetch-request-browser'; | ||
await send( | ||
'https://httpbin.org/get', | ||
await sendGET( | ||
'https://httpbin.org/get?someUid=5', | ||
{ | ||
requestOptions: { | ||
method: 'GET' | ||
} | ||
credentials: 'include', | ||
}, | ||
acceptableStatusCodes: [200, 201], | ||
}, | ||
@@ -42,5 +39,5 @@ [3, 5, 10] | ||
// headers: Headers { | ||
// date: 'Tue, 04 Jun 2024 18:52:29 GMT', | ||
// date: 'Fri, 06 Dec 2024 14:14:12 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '407', | ||
// 'content-length': '399', | ||
// connection: 'keep-alive', | ||
@@ -52,3 +49,3 @@ // server: 'gunicorn/19.9.0', | ||
// data: { | ||
// args: {}, | ||
// args: { someUid: '5' }, | ||
// headers: { | ||
@@ -58,2 +55,53 @@ // Accept: 'application/json', | ||
// 'Accept-Language': '*', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-675306b4-175937342b1b6ffa6ddbaaee' | ||
// }, | ||
// origin: '136.144.19.103', | ||
// url: 'https://httpbin.org/get?someUid=5' | ||
// } | ||
// } | ||
``` | ||
Send a `POST` request that will retry (up to 3 times) on failure to [HTTPBin](https://httpbin.org/): | ||
```typescript | ||
import { sendGET } from 'fetch-request-browser'; | ||
await sendPOST( | ||
'https://httpbin.org/post?id=1', | ||
{ | ||
requestOptions: { | ||
body: { | ||
someKey: 'Hello', | ||
someNumber: 123456, | ||
}, | ||
credentials: 'include', | ||
}, | ||
acceptableStatusCodes: [200, 201], | ||
}, | ||
[3, 5, 10] | ||
); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 12:57:25 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '619', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: { id: '1' }, | ||
// data: '{"someKey":"Hello","someNumber":123456}', | ||
// files: {}, | ||
// form: {}, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// 'Content-Length': '39', | ||
// 'Content-Type': 'application/json', | ||
@@ -63,6 +111,7 @@ // Host: 'httpbin.org', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': '...' | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752f4b5-76a61b597284afb62df479eb' | ||
// }, | ||
// origin: '...', | ||
// url: 'https://httpbin.org/get' | ||
// json: { someKey: 'Hello', someNumber: 123456 }, | ||
// origin: '136.144.19.233', | ||
// url: 'https://httpbin.org/post?id=1' | ||
// } | ||
@@ -78,112 +127,424 @@ // } | ||
## API | ||
## API Reference | ||
Build and send an HTTP Request (any method): | ||
<details> | ||
<summary><code>send</code></summary> | ||
```typescript | ||
send( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends an HTTP Request based on the provided input and options. | ||
```typescript | ||
await send( | ||
'https://httpbin.org/get?foo=hey&bar=123', { | ||
requestOptions: { method: 'GET' } | ||
} | ||
); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:05:20 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '422', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: { bar: '123', foo: 'hey' }, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752f690-43ddfac50ee723b532cf3cf3' | ||
// }, | ||
// origin: '136.144.19.106', | ||
// url: 'https://httpbin.org/get?foo=hey&bar=123' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>sendGET</code></summary> | ||
Build and send a `GET` HTTP Request: | ||
```typescript | ||
sendGET( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends a `GET` HTTP Request based on the provided input and options. | ||
```typescript | ||
await sendGET('https://httpbin.org/get?foo=hey&bar=123'); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:05:20 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '422', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: { bar: '123', foo: 'hey' }, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752f690-43ddfac50ee723b532cf3cf3' | ||
// }, | ||
// origin: '136.144.19.106', | ||
// url: 'https://httpbin.org/get?foo=hey&bar=123' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>sendPOST</code></summary> | ||
Build and send a `POST` HTTP Request: | ||
```typescript | ||
sendPOST( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends a `POST` HTTP Request based on the provided input and options. | ||
```typescript | ||
await sendPOST( | ||
'https://httpbin.org/post', | ||
{ | ||
requestOptions: { | ||
body: { | ||
someKey: 'Hello', | ||
someNumber: 123456, | ||
}, | ||
}, | ||
}, | ||
); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:13:18 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '596', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: {}, | ||
// data: '{"someKey":"Hello","someNumber":123456}', | ||
// files: {}, | ||
// form: {}, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// 'Content-Length': '39', | ||
// 'Content-Type': 'application/json', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752f86e-366f8cb71596c46374885670' | ||
// }, | ||
// json: { someKey: 'Hello', someNumber: 123456 }, | ||
// origin: '136.144.19.99', | ||
// url: 'https://httpbin.org/post' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>sendPUT</code></summary> | ||
Build and send a `PUT` HTTP Request: | ||
```typescript | ||
sendPUT( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends a `PUT` HTTP Request based on the provided input and options. | ||
```typescript | ||
await sendPUT( | ||
'https://httpbin.org/put', | ||
{ | ||
requestOptions: { | ||
body: { | ||
someKey: 'Hello', | ||
someNumber: 123456, | ||
}, | ||
}, | ||
}, | ||
); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:19:07 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '596', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: {}, | ||
// data: '{"someKey":"Hello","someNumber":123456}', | ||
// files: {}, | ||
// form: {}, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// 'Content-Length': '39', | ||
// 'Content-Type': 'application/json', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752f9cb-4633cbc111fccdc020c15081' | ||
// }, | ||
// json: { someKey: 'Hello', someNumber: 123456 }, | ||
// origin: '136.144.19.122', | ||
// url: 'https://httpbin.org/put' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>sendPATCH</code></summary> | ||
Build and send a `PATCH` HTTP Request: | ||
```typescript | ||
sendPATCH( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends a `PATCH` HTTP Request based on the provided input and options. | ||
```typescript | ||
await sendPATCH( | ||
'https://httpbin.org/patch', | ||
{ | ||
requestOptions: { | ||
body: { | ||
someKey: 'Hello', | ||
someNumber: 123456, | ||
}, | ||
}, | ||
}, | ||
); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:22:54 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '597', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: {}, | ||
// data: '{"someKey":"Hello","someNumber":123456}', | ||
// files: {}, | ||
// form: {}, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// 'Content-Length': '39', | ||
// 'Content-Type': 'application/json', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752faae-7da3d0d33f55d85f1f563abb' | ||
// }, | ||
// json: { someKey: 'Hello', someNumber: 123456 }, | ||
// origin: '136.144.19.93', | ||
// url: 'https://httpbin.org/patch' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>sendDELETE</code></summary> | ||
Build and send a `DELETE` HTTP Request: | ||
```typescript | ||
sendDELETE( | ||
input: IRequestInput, | ||
options?: Partial<IOptions>, | ||
retryDelaySchedule?: number[], | ||
): Promise<IRequestResponse> | ||
``` | ||
Builds and sends a `DELETE` HTTP Request based on the provided input and options. | ||
```typescript | ||
await sendDELETE('https://httpbin.org/delete?id=1'); | ||
// { | ||
// code: 200, | ||
// headers: Headers { | ||
// date: 'Fri, 06 Dec 2024 13:25:41 GMT', | ||
// 'content-type': 'application/json', | ||
// 'content-length': '496', | ||
// connection: 'keep-alive', | ||
// server: 'gunicorn/19.9.0', | ||
// 'access-control-allow-origin': '*', | ||
// 'access-control-allow-credentials': 'true' | ||
// }, | ||
// data: { | ||
// args: { id: '1' }, | ||
// data: '', | ||
// files: {}, | ||
// form: {}, | ||
// headers: { | ||
// Accept: 'application/json', | ||
// 'Accept-Encoding': 'br, gzip, deflate', | ||
// 'Accept-Language': '*', | ||
// 'Content-Type': 'application/json', | ||
// Host: 'httpbin.org', | ||
// 'Sec-Fetch-Mode': 'cors', | ||
// 'User-Agent': 'node', | ||
// 'X-Amzn-Trace-Id': 'Root=1-6752fb55-62da6f1d3348e8a55af75ae3' | ||
// }, | ||
// json: null, | ||
// origin: '136.144.19.240', | ||
// url: 'https://httpbin.org/delete?id=1' | ||
// } | ||
// } | ||
``` | ||
</details> | ||
<br /> | ||
## Built With | ||
## Types | ||
- TypeScript | ||
<details> | ||
<summary><code>IRequestInput</code></summary> | ||
The URL of the request's target. | ||
```typescript | ||
type IRequestInput = string | URL; | ||
``` | ||
</details> | ||
<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> | ||
<br /> | ||
<details> | ||
<summary><code>IRequestMethod</code></summary> | ||
## Running the Tests | ||
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> | ||
```bash | ||
# Unit Tests | ||
$ npm run test:unit | ||
<details> | ||
<summary><code>RequestInit</code></summary> | ||
# Integration Tests | ||
$ npm run test:integration | ||
``` | ||
The [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit) dictionary of the Fetch API represents the set of options that can be used to configure a fetch request. | ||
```typescript | ||
interface RequestInit { | ||
/** A BodyInit object or null to set request's body. */ | ||
body?: BodyInit | null; | ||
/** A string indicating how the request will interact with the browser's cache to set request's cache. */ | ||
cache?: RequestCache; | ||
/** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */ | ||
credentials?: RequestCredentials; | ||
/** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ | ||
headers?: HeadersInit; | ||
/** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ | ||
integrity?: string; | ||
/** A boolean to set request's keepalive. */ | ||
keepalive?: boolean; | ||
/** A string to set request's method. */ | ||
method?: string; | ||
/** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */ | ||
mode?: RequestMode; | ||
priority?: RequestPriority; | ||
/** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ | ||
redirect?: RequestRedirect; | ||
/** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */ | ||
referrer?: string; | ||
/** A referrer policy to set request's referrerPolicy. */ | ||
referrerPolicy?: ReferrerPolicy; | ||
/** An AbortSignal to set request's signal. */ | ||
signal?: AbortSignal | null; | ||
/** Can only be null. Used to disassociate request from any Window. */ | ||
window?: null; | ||
} | ||
``` | ||
</details> | ||
<details> | ||
<summary><code>IRequestOptions</code></summary> | ||
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. | ||
```typescript | ||
interface IRequestOptions extends RequestInit { | ||
method: IRequestMethod; // this lib only makes use of these methods | ||
body: any; | ||
} | ||
``` | ||
</details> | ||
<details> | ||
<summary><code>IResponseDataType</code></summary> | ||
The type of data that will be extracted from the HTTP Response body. | ||
```typescript | ||
type IResponseDataType = 'arrayBuffer' | 'blob' | 'formData' | 'json' | 'text'; | ||
``` | ||
</details> | ||
<br /> | ||
<details> | ||
<summary><code>IOptions</code></summary> | ||
## License | ||
The options object that can be passed and used for any request. | ||
```typescript | ||
interface IOptions { | ||
// the options that will be used to build the request | ||
requestOptions?: Partial<IRequestOptions>; | ||
[MIT](https://choosealicense.com/licenses/mit/) | ||
// the expected data type that should be extracted from the response | ||
responseDataType: IResponseDataType; | ||
/** | ||
* Response Status Codes | ||
* The request's response can be validated by providing a list of acceptable codes or a range | ||
* object. Keep in mind that if the acceptableStatusCodes array is provided, it will only perform | ||
* that validation and ignore the acceptableStatusCodesRange. | ||
*/ | ||
// the list of status codes that won't throw an error | ||
acceptableStatusCodes?: number[]; | ||
// the range of codes that are considered to be acceptable. Defaults to: { min: 200, max: 299 } | ||
acceptableStatusCodesRange: { min: number, max: number }; | ||
// if enabled, it will not validate the status code from the response object | ||
skipStatusCodeValidation: boolean; | ||
} | ||
``` | ||
</details> | ||
<details> | ||
<summary><code>IRequestResponse</code></summary> | ||
The object containing the result of the Request. | ||
```typescript | ||
interface IRequestResponse { | ||
// the HTTP status code extracted from the Response | ||
code: number; | ||
// the Response's Headers. Useful as some service providers attach important info in the headers | ||
headers: Headers; | ||
// the data extracted from the Response Instance | ||
data: any; | ||
} | ||
``` | ||
</details> | ||
<br /> | ||
## Acknowledgments | ||
## Built With | ||
- [MDN](https://developer.mozilla.org/en-US/) | ||
- [web.dev](https://web.dev/) | ||
- TypeScript | ||
@@ -193,8 +554,23 @@ | ||
<br /> | ||
## Running the Tests | ||
```bash | ||
# unit tests | ||
npm run test:unit | ||
# integration tests | ||
npm run test:integration | ||
``` | ||
<br /> | ||
## @TODOS | ||
## License | ||
- [ ] Improve the docs | ||
[MIT](https://choosealicense.com/licenses/mit/) | ||
@@ -211,3 +587,3 @@ | ||
```bash | ||
$ npm install | ||
npm install | ||
``` | ||
@@ -218,3 +594,3 @@ | ||
```bash | ||
$ npm start | ||
npm start | ||
``` | ||
@@ -225,3 +601,3 @@ | ||
```bash | ||
$ npm publish | ||
npm publish | ||
``` |
34806
593
2
209
+ Addedweb-utils-kit@^1.0.3
+ Addedcall-bind@1.0.8(transitive)
+ Addedcall-bind-apply-helpers@1.0.2(transitive)
+ Addedcall-bound@1.0.3(transitive)
+ Addeddefine-data-property@1.1.4(transitive)
+ Addeddunder-proto@1.0.1(transitive)
+ Addedes-define-property@1.0.1(transitive)
+ Addedes-errors@1.3.0(transitive)
+ Addedes-object-atoms@1.1.1(transitive)
+ Addedfunction-bind@1.1.2(transitive)
+ Addedget-intrinsic@1.3.0(transitive)
+ Addedget-proto@1.0.1(transitive)
+ Addedgopd@1.2.0(transitive)
+ Addedhas-property-descriptors@1.0.2(transitive)
+ Addedhas-symbols@1.1.0(transitive)
+ Addedhasown@2.0.2(transitive)
+ Addedisarray@2.0.5(transitive)
+ Addedjson-stable-stringify@1.2.1(transitive)
+ Addedjsonify@0.0.1(transitive)
+ Addedmath-intrinsics@1.1.0(transitive)
+ Addedobject-keys@1.1.1(transitive)
+ Addedset-function-length@1.2.2(transitive)
+ Addeduuid@11.1.0(transitive)
+ Addedweb-utils-kit@1.0.5(transitive)
Updatederror-message-utils@^1.1.2