1.0.0 • Published 7 months ago

reqiox v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
7 months ago

Reqiox

Reqiox is a flexible and feature-rich library for making HTTP requests in JavaScript applications. It provides capabilities for request interception, response interception, request cancellation, retry mechanisms, and caching.

Features

  • Request Methods: Supports GET, POST, PUT, DELETE methods.
  • Request Interceptors: Customize or transform requests before they are sent.
  • Response Interceptors: Handle and modify responses received from requests.
  • AbortController: Cancel ongoing requests gracefully using AbortController.
  • Retry Mechanism: Automatic retry with exponential backoff for failed requests.
  • Caching: In-memory caching of responses with configurable expiration.

Installation

Install Reqiox via npm:

npm install reqiox --save
import ReqioxClient from 'reqiox';

// Initialize ReqioxClient with base URL
const api = new ReqioxClient('https://api.example.com');

// Add request interceptors (optional)
api.addRequestInterceptor(async (options) => {
  // Modify headers, add authentication tokens, etc.
  return options;
});

// Add response interceptors (optional)
api.addResponseInterceptor(async (response) => {
  // Handle global error responses, transform data, etc.
  return response;
});

// Make GET request
api.get('/posts')
  .then(data => console.log('GET Response:', data))
  .catch(error => console.error('GET Error:', error));

// Make POST request
api.post('/posts', { title: 'New Post', body: 'Content' })
  .then(data => console.log('POST Response:', data))
  .catch(error => console.error('POST Error:', error));

// Cancel a request
api.cancelRequest('/posts', 'GET');

// Clear cache for a specific endpoint
api.clearCache('/posts');

// Retry a request with exponential backoff
api.requestWithRetry('/posts', { method: 'GET' })
  .then(data => console.log('Retry Response:', data))
  .catch(error => console.error('Retry Error:', error));

Library Reference

new ReqioxClient(baseURL)

Creates a new instance of ReqioxClient with the specified base URL.

  • baseURL: Base URL for API requests.

api.addRequestInterceptor(interceptor)

Adds a request interceptor function that will be called before sending a request.

  • interceptor: Function that receives the current request options and returns modified options.

api.addResponseInterceptor(interceptor)

Adds a response interceptor function that will be called when a response is received.

  • interceptor: Function that receives the response object and returns modified response or handles errors.

HTTP Methods

api.get(endpoint, options)

Makes a GET request to the specified endpoint.

  • endpoint: API endpoint.
  • options: Optional request options (e.g., headers, timeout).

api.post(endpoint, body, options)

Makes a POST request to the specified endpoint.

  • endpoint: API endpoint.
  • body: Request body object.
  • options: Optional request options (e.g., headers, timeout).

api.put(endpoint, body, options)

Makes a PUT request to the specified endpoint.

  • endpoint: API endpoint.
  • body: Request body object.
  • options: Optional request options (e.g., headers, timeout).

api.delete(endpoint, options)

Makes a DELETE request to the specified endpoint.

  • endpoint: API endpoint.
  • options: Optional request options (e.g., headers, timeout).

Other Methods

api.cancelRequest(endpoint, method)

Cancels an ongoing request with the specified endpoint and HTTP method.

  • endpoint: API endpoint.
  • method: HTTP method (e.g., GET, POST).

api.clearCache(endpoint)

Clears cached response for the specified endpoint.

  • endpoint: API endpoint.

api.requestWithRetry(endpoint, options, retries)

Retries a failed request with exponential backoff.

  • endpoint: API endpoint.
  • options: Optional request options (e.g., headers, timeout).
  • retries: Optional number of retry attempts (default: 3).
acornacorn-jsxajvansi-escapesansi-regexansi-stylesanymatchargparsebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbinary-extensionsbrace-expansionbracesbrowserslistbserbuffer-fromcallsitescamelcasecaniuse-litechalkchar-regexchokidarci-infocjs-module-lexercliuicocollect-v8-coveragecolor-convertcolor-namecommanderconcat-mapconvert-source-mapcore-js-compatcreate-jestcross-spawndebugdedentdeep-isdeepmergedetect-newlinediff-sequenceselectron-to-chromiumemitteryemoji-regexerror-exescaladeescape-string-regexpeslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsexecaexitexpectfast-deep-equalfast-json-stable-stringifyfast-levenshteinfastqfb-watchmanfile-entry-cachefill-rangefind-upflat-cacheflattedfs-readdir-recursivefs.realpathfunction-bindgensyncget-caller-fileget-package-typeget-streamglobglob-parentgraceful-fshas-flaghasownhtml-escaperhuman-signalsignoreimport-freshimport-localimurmurhashinflightinheritsis-arrayishis-binary-pathis-core-moduleis-extglobis-fullwidth-code-pointis-generator-fnis-globis-numberis-path-insideis-streamisexeistanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjs-tokensjs-yamljsescjson-bufferjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson5keyvkleurlevenlevnlines-and-columnslocate-pathlodash.debouncelodash.mergelru-cachemake-dirmakeerrormerge-streammicromatchmimic-fnminimatchmsnatural-comparenode-int64node-releasesnormalize-pathnpm-run-pathonceonetimeoptionatorp-limitp-locatep-tryparent-moduleparse-jsonpath-existspath-is-absolutepath-keypath-parsepicocolorspicomatchpifypiratespkg-dirprelude-lspretty-formatpromptspunycodepure-randqueue-microtaskreact-isreaddirpregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexpu-coreregjsparserrequire-directoryresolveresolve-cwdresolve-fromresolve.exportsreusifyrun-parallelsemvershebang-commandshebang-regexsignal-exitsisteransislashsource-mapsource-map-supportsprintf-jsstack-utilsstring-lengthstring-widthstrip-ansistrip-bomstrip-final-newlinestrip-json-commentssupports-colorsupports-preserve-symlinks-flagtest-excludetext-tabletmplto-fast-propertiesto-regex-rangetype-checktype-detecttype-festundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptupdate-browserslist-dburi-jsv8-to-istanbulwalkerwhichword-wrapwrap-ansiwrappywrite-file-atomicy18nyallistyargsyargs-parseryocto-queue
1.0.0

7 months ago