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.
npm i kwest-giver
To use KwestGiver
in your project, simply import it as follows:
import KwestGiver from './KwestGiver';
Initialize the KwestGiver
class by providing an optional API URL:
const kwest = new KwestGiver('https://api.example.com');
// https://api.example.com/endpoint
kwest.get('/endpoint')
.then(response => console.log(response))
.catch(error => console.error(error));
// https://api.example.com/endpoint
const body = { key: 'value' };
kwest.post('/endpoint', body)
.then(response => console.log(response))
.catch(error => console.error(error));
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);
};
constructor(url)
-
url
(optional): The base URL for the API.
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')
Toggles the use of the request queue.
toggleQueue()
Sets the base API URL.
addApiUrl(url)
-
url
: The base URL for the API.
Makes a fetch request to a specified URL with a given configuration.
fetchQuest(url, config)
-
url
: The request URL. -
config
: The request configuration object.
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.
Makes a GET request.
get(url, config = {})
-
url
: The request URL. -
config
: The request configuration object.
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.
Makes a POST request.
post(url, body, config = {})
-
url
: The request URL. -
body
: The request body. -
config
: The request configuration object.
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.
Makes a PUT request.
put(url, body, config = {})
-
url
: The request URL. -
body
: The request body. -
config
: The request configuration object.
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.
Makes a DELETE request.
delete(url, config = {})
-
url
: The request URL. -
config
: The request configuration object.
Converts JSON to a query string.
queryString(JSON)
Parses a query string to a JSON object.
decodeQueryString(queryString)
Sets the token lifecycle.
setLifecycle(span)
-
span
: The token lifecycle span.
Handles the request queue and lifecycle.
QuestBoard(url, config, method)
-
url
: The request URL. -
config
: The request configuration object. -
method
: The HTTP method.
Creates a WebSocket connection.
webSocket(url)
-
url
: The WebSocket URL.
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))
))
})
})
Set a function to return a Name/Value object for authorization in use with localKeys.
kwest.setAuthorization(keyFromStorage => ({ authorization: 'Bearer ' + keyFromStorage.accessToken }))
Logs the current header keys.
showHeaderKeys()
Checks if a header key exists.
hasHeaderKey(key)
-
key
: The key to check.
Clears all header keys.
clearHeaderKeys()
Adds a header key.
addHeaderKeyValue(keyValue)
-
keyValue
: The key to add.
Replaces a header key.
replaceHeaderKeyValue(keyValue)
-
keyValue
: The key to replace.
Removes a header key.
removeHeaderKey(key)
-
key
: The key to remove.
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 = {})
Errors are handled and categorized as follows:
-
server
: Server errors. -
loggedOut
: Unauthorized errors. -
unauthorized
: Forbidden errors. -
message
: General errors.
This project is licensed under the MIT License.