kwest-giver

1.1.8 • Public • Published

KwestGiver

KwestGiver is a JavaScript class designed to simplify and streamline API requests and WebSocket connections. It offers support for various HTTP methods, queueing of requests, and middleware capabilities.

Table of Contents

Installation

npm i kwest-giver

To use KwestGiver in your project, simply import it as follows:

import KwestGiver from './KwestGiver';

Usage

Initialize the KwestGiver class by providing an optional API URL:

const kwest = new KwestGiver('https://api.example.com');

Basic GET Request

// https://api.example.com/endpoint
kwest.get('/endpoint')
    .then(response => console.log(response))
    .catch(error => console.error(error));

POST Request with JSON Body

// https://api.example.com/endpoint
const body = { key: 'value' };
kwest.post('/endpoint', body)
    .then(response => console.log(response))
    .catch(error => console.error(error));

WebSocket Connection

const kwest = new KwestGiver();

const socket = kwest.webSocket('wss://example.com/socket');

socket.onmessage = function(message) {
    // message is in JSON (if parsable)
    console.log('Message from server ', message);
};

Methods

Constructor

constructor(url)
  • url (optional): The base URL for the API.

use

To add middleware, use the use method. The middleware function will receive the HTTP header config object or http result, which you can modify as needed.

use(middleware, type = 'pre')
  • middleware: A function that takes the HTTP header config object as its argument.
  • type: Where the middleware gets executed. (pre/post) the http request.
kwest.use(config => {
    try {
        const keys = getLocal('HSQuestKeys');
        Object.assign(config.headers, { authorization: 'Bearer ' + keys.access })
    } catch {
        console.warn('Keys Missing.')
    }
})

kwest.use(config => {
    if (res.success === true) {
        return res.resultData;
    }

    if (res.success === false) {
        const errorMessage = {
            errorMessage: res.errorMessage || 'An Error has occurred...'
        };
        throw errorMessage;
    }
}, 'post')

toggleQueue

Toggles the use of the request queue.

toggleQueue()

addApiUrl

Sets the base API URL.

addApiUrl(url)
  • url: The base URL for the API.

fetchQuest

Makes a fetch request to a specified URL with a given configuration.

fetchQuest(url, config)
  • url: The request URL.
  • config: The request configuration object.

config

The request configuration object that can take custom headers for further features.

  • captcha: Add a reCAPTCHA site key to the config to add the reCAPTCHA token to the request.

HTTP Methods

get

Makes a GET request.

get(url, config = {})
  • url: The request URL.
  • config: The request configuration object.

getQuery

Makes a GET request with query parameters.

getQuery(url, query, config = {})
  • url: The request URL.
  • query: The query parameters as an object.
  • config: The request configuration object.

post

Makes a POST request.

post(url, body, config = {})
  • url: The request URL.
  • body: The request body.
  • config: The request configuration object.

postFile

Uploads a file using a POST request.

postFile(url, files, key = 'file', config = {})
  • url: The request URL.
  • files: The files to upload.
  • key: The form data key (default is 'file').
  • config: The request configuration object.

put

Makes a PUT request.

put(url, body, config = {})
  • url: The request URL.
  • body: The request body.
  • config: The request configuration object.

patch

Makes a PATCH request.

patch(url, body, operation, config = {})
  • url: The request URL.
  • body: The request body.
  • operation: The patch operation (update, add, remove, copy, move, test).
  • config: The request configuration object.

delete

Makes a DELETE request.

delete(url, config = {})
  • url: The request URL.
  • config: The request configuration object.

queryString

Converts JSON to a query string.

queryString(JSON)

decodeQueryString

Parses a query string to a JSON object.

decodeQueryString(queryString)

setLifecycle

Sets the token lifecycle.

setLifecycle(span)
  • span: The token lifecycle span.

QuestBoard

Handles the request queue and lifecycle.

QuestBoard(url, config, method)
  • url: The request URL.
  • config: The request configuration object.
  • method: The HTTP method.

WebSocket

Creates a WebSocket connection.

webSocket(url)
  • url: The WebSocket URL.

Header Keys Management

setUnauthorized

Set a function to be called on a 401 Unauthorized error when hitting the saved API endpoint. This function is typically used to handle authentication refresh and retry failed requests.

kwest.setUnauthorized((url, config) => {
    return new Promise((resolve, reject) => {
        updateAccessToken()
            .then(() => (
                kwest.fetchQuest(url, config)
                    .then(res => resolve(res))
                    .catch(ex => reject(ex))
            ))
    })
})

setAuthorization

Set a function to return a Name/Value object for authorization in use with localKeys.

kwest.setAuthorization(keyFromStorage => ({ authorization: 'Bearer ' + keyFromStorage.accessToken }))

showHeaderKeys

Logs the current header keys.

showHeaderKeys()

hasHeaderKey

Checks if a header key exists.

hasHeaderKey(key)
  • key: The key to check.

clearHeaderKeys

Clears all header keys.

clearHeaderKeys()

addHeaderKeyValue

Adds a header key.

addHeaderKeyValue(keyValue)
  • keyValue: The key to add.

replaceHeaderKeyValue

Replaces a header key.

replaceHeaderKeyValue(keyValue)
  • keyValue: The key to replace.

removeHeaderKey

Removes a header key.

removeHeaderKey(key)
  • key: The key to remove.

Static Methods

KwestGiver provides static methods for convenience:

fetchQuest(url, config)
get(url, config = {})
getQuery(url, query, config = {})
queryString(query)
post(url, body, config = {})
put(url, body, config = {})
patch(url, body, operation, config = {})
delete(url, config = {})

Error Handling

Errors are handled and categorized as follows:

  • server: Server errors.
  • loggedOut: Unauthorized errors.
  • unauthorized: Forbidden errors.
  • message: General errors.

License

This project is licensed under the MIT License.

Package Sidebar

Install

npm i kwest-giver

Weekly Downloads

0

Version

1.1.8

License

MIT

Unpacked Size

23.2 kB

Total Files

3

Last publish

Collaborators

  • zwkitcher