npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

kwest-giver

v1.1.8

Published

Async HTTP client for JS environments.

Downloads

5

Readme

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.