Skip to content

Documenation

ksplat edited this page Sep 2, 2021 · 4 revisions

Welcome to the AxleJS documentation!

This Github Wiki serves as documentation for AxleJS.

Documentation for version 1.1.1.

Exports

Axle Object

The Axle Object is the default export of AxleJS. It includes all HTTP Restful Methods, middleware, middleware options, cancelMark, all (Promise.all), use, and useOptions.

const Axle = {
	post: post,
	get: get,
	delete: deleteReq,
	put: put,
	patch: patch,
	head: head,
	all: (promises: Promise<AxleResponse | undefined>[]) => {
		return Promise.all(promises);
	},
	cancelMark: AxleCancelMark,
	use: use,
	useOptions: useOptions,
	middleware: {
		timeTook: timeTook,
	},
	middlewareOptions: {
		cors: cors,
		kneepads: kneepads,
	},
};

AxleTypes

AxleTypes is the 2nd export of AxleJS. It has all types for AxleJS and is only for Typescript users. It includes AxleOptions, AxleMiddleware, and AxleError.

export namespace AxleTypes {
	export interface AxleOptions {
		mode?: 'no-cors' | 'cors' | 'same-origin';
		cache?:
			| 'no-cache'
			| 'default'
			| 'reload'
			| 'force-cache'
			| 'only-if-cached';
		credentials?: RequestCredentials;
		headers?: AxleHeaders;
		redirect?: 'manual' | 'follow' | 'error';
		referrer?: string;
		referrerPolicy?:
			| 'no-referrer'
			| 'no-referrer-when-downgrade'
			| 'origin'
			| 'origin-when-cross-origin'
			| 'same-origin'
			| 'strict-origin'
			| 'strict-origin-when-cross-origin'
			| 'unsafe-url';
		body?: string | FormData;
		keepalive?: boolean;
		signal?: AbortSignal | null;
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		window?: any;
		integrity?: string;
		handleStatus?: (status: number, statusMessage: string) => boolean;
	}

	export type AxleMiddleware = (
		req: AxleRequest,
		res: AxleResponse
	) => unknown;

	export interface AxleError {
		status: number;
		message: string;
		response: AxleResponse;
		request: AxleRequest;
	}
}

API

Making HTTP Requests

AxleJS has all HTTP Restful Methods which is GET, POST, PUT, PATCH, and DELETE. AxleJS also has the HEAD method.

Example:

import Axle from 'pathToAxle';

(async function () {

    const res = await Axle.post('https://example.com/test'); // response is returned if no errors

    const json = await res.json();

    return json;
})()

All HTTP Restful Methods

Axle.get(...)

Makes a GET request to the provided URL.

Parameters
- 1 2
Parameter URL Options
Type String AxleOptions
Default - { mode: 'cors', cache: 'default' }
Return Value

AxleResponse


Axle.head(...)

Makes a HEAD request to the provided URL.

Parameters
- 1 2
Parameter URL Options
Type String AxleOptions
Default - { mode: 'cors', cache: 'default' }
Return Value

AxleResponse


Axle.post(...)

Makes a POST request to the provided URL.

Parameters
- 1 2 3
Parameter URL Data Options
Type String Object | FormData AxleOptions
Default - {} mode: 'cors', cache: 'default', credentials: 'same-origin', headers: { 'Content-Type': 'application/json'}}`
Return Value

AxleResponse


Axle.put(...)

Makes a PUT request to the provided URL.

Parameters
- 1 2 3
Parameter URL Data Options
Type String Object | FormData AxleOptions
Default - {} mode: 'cors', cache: 'default', credentials: 'same-origin', headers: { 'Content-Type': 'application/json'}}`
Return Value

AxleResponse


Axle.patch(...)

Makes a PATCH request to the provided URL.

Parameters
- 1 2 3
Parameter URL Data Options
Type String Object | FormData AxleOptions
Default - {} mode: 'cors', cache: 'default', credentials: 'same-origin', headers: { 'Content-Type': 'application/json'}}`
Return Value

AxleResponse


Axle.delete(...)

Makes a DELETE request to the provided URL.

Parameters
- 1 2 3
Parameter URL Data Options
Type String Object | FormData AxleOptions
Default - {} mode: 'cors', cache: 'default', credentials: 'same-origin', headers: { 'Content-Type': 'application/json'}}`
Return Value

AxleResponse


Middleware

AxleJS Middleware is a function callback that is applied/ run on every request.

Built-ins

  • timeTook - Logs and measures the time it took to complete the request.

Using Middleware

AxleJS has build in middleware such as timeTook located in the middleware object in Axle.
To use middleware, call Axle.use().
Example:

import Axle from 'pathToAxle';

Axle.use(Axle.middleware.timeTook());

Using Custom Middleware

Axle.use takes a callback function with two parameters being AxleRequest, and AxleResponse.
Example:

import Axle from 'pathToAxle';

Axle.use((req, res) => {
   console.log(res.url, res.status);
});

Creating Middleware Functions

A middleware function must return a callback that is a AxleMiddleware.
Example:

import Axle from 'pathToAxle';

function customMiddlewareFunction() {
    // return callback
    return (req, res) => {
        res.redirect('https://example.com');
    }
}

Axle.use(customMiddlewareFunction());

Middleware Options

AxleJS Middleware Options is an AxleOptions object that is applied to every request's options.

Built-ins

  • cors - Sets mode -> cors, and cache -> default
  • kneepads - Sets credentials -> omit, referrer -> '', and referrerPolicy -> no-referrer

Using Middleware Options

AxleJS allows to store AxleOptions as a return in functions to use as a Axle Middleware Option.
AxleJS has built-in middleware options such as cors, and kneepads.
Example:

import Axle from 'pathToAxle';

Axle.useOptions({
    ...Axle.middlewareOptions.cors(),
    ...Axle.middlewareOptions.kneepads(),
})

// OR

Axle.useOptions(Axle.middlewareOptions.cors())
Axle.useOptions(Axle.middlewareOptions.kneepads())

Using Custom Middleware Options

Axle.useOptions takes an AxleOptions object.
Example:

import Axle from 'pathToAxle';

Axle.useOptions({
    // custom options
    mode: 'no-cors',
    cache: 'default'
})

AxleResponse

Methods

async json<t = Record<string, unknown>>(): Promise

Returns parsed JSON that was received.

async data(): Promise

Returns the text that was received.

async body(): Promise<Uint8Array | undefined>

Returns the data that was read from the bodyReader.

redirect(url: string | URL, ifStatusOk = true): void

Redirects to a URL.

finishRedirect(): true | null

Automatically follows redirect by new Location Header.

async blob(): Promise

Returns the Blob that was received.

queryParam(name: string): string | null

Returns the query parameter by name or null if not found.

Getters

bodyReader: ReadableStream | null

Returns ReadableStream | null from the received body.

bodyUsed: boolean

Returns a boolean based on if the body has been processed.

status: number

Returns the status of the response.

statusMessage: string

Returns the status message of the response.

url: string

Returns the URL of the response.

query: Object

Returns an object of the query string in the response url.

headers: AxleHeaders

Returns headers of the response in AxleHeaders.

timeTook: number

Returns the amount of milliseconds it took to complete the request.

type: ResponseType

Returns the response type of the response.

basic: Response

Returns a normal fetch response instead of using AxleResponse.


AxleHeaders

Methods

append(name: string, value: string): void

Appends a header.

delete(name: string): boolean

Deletes a header. Returns boolean based on if deleted or not.

deleteByValue(value: string): boolean

Deletes a header by value. Returns boolean based on if deleted or not.

get(name: string): string | null

Returns the value of a header by its name.

getByValue(value: string): string | null

Returns the name of a header by its value.

set(name: string, value: string, ifExists = false): boolean

Sets the value of a header by its name.

has(name: string): boolean

Checks if a header exists by its name.

hasValue(value: string): boolean | undefined

Checks if a header exists by its value.

each( cb: <t = unknown>(name: string, value: string, index: number) => t )

Loops through each header and calls a callback passing the name, value, and index.

keys(): IterableIterator

Returns the names of the headers.

values(): IterableIterator

Returns the values of the headers.

keyArray(): string[]

Returns the names of the headers as an array.

valueArray(): string[]

Returns the values of the headers as an array.

object(): Object

Converts Headers into an Object.

is(name: string, value: string): boolean | null

Checks if a header is equal to a value. Returns boolean if exists and null if header does not exist.

includesValue(name: string, value: string): boolean | null

Checks if a header's value has part of a passed value. Returns boolean if exists and null if header does not exist.

Getters

entries: IterableIterator<[string, string]>

Returns the header's entries.

basic: Headers

Returns Headers instead of AxleHeaders.


AxleCancelMark

Methods

cancel(message?: string): void

Runs AbortController.abort() to cancel the request and if a message is passed it also runs console.error(message).

Properties

signal: AbortSignal

The AbortSignal to pass to your request's signal option. Needed to run AxleCancelMark.cancel().

How to use

AxleCancelMark uses an AbortController and an AbortSignal to cancel a request.
Example:

import Axle from 'pathToAxle'

const cancelMark = new Axle.CancelMark();
const cancelSignal = cancelMark.signal;

Axle.get('https://example.com/test', {
    signal: cancelSignal
    // ... your options
}).then((res) => {
   // ...
}).catch((e) => {
   // ...
})

// cancel
cancelMark.cancel('Canceled request!')

Other Axle Methods and Properties

Axle.all([])

Uses Promise.all() to run multiple AxleRequests.

Parameters
- 1
Parameter promises
Type Promise[]
Default -
Return Value

Promise<AxleRequest>[]


Axle.cancelMark

The AxleCancelMark class exported as a property of the Axle Object.

Type

AxleCancelMark


Axle.use()

Tells Axle to use a middleware function.

Parameters
- 1
Parameter middleware
Type AxleMiddleware
Default -
Return Value

Number


Axle.useOptions()

Tells Axle to use a middleware option.

Parameters
- 1
Parameter middlewareOption
Type AxleOptions
Default -
Return Value

Number


Clone this wiki locally