KoAJAX

KoAJAX

HTTP Client based on Koa-like middlewares

NPM Dependency CI & CD

NPM

Usage

Browser

npm install koajax

index.html

<head>
<script src="https://polyfill.web-cell.dev/feature/Regenerator.js"></script>
<script src="https://polyfill.web-cell.dev/feature/ECMAScript.js"></script>
</head>

Node.js

npm install koajax jsdom

index.js

import { HTTPClient } from 'koajax';
import { polyfill } from 'koajax/source/polyfill'

const origin = 'https://your-target-origin.com';

polyfill(origin).then(() => {
const client = new HTTPClient({
baseURI: `${origin}/api`,
responseType: 'json'
});
const { body } = await client.get('test/interface');

console.log(body);
});

Example

RESTful API with Token-based Authorization

import { HTTPClient } from 'koajax';

var token = '';

export const client = new HTTPClient().use(
async ({ request: { method, path, headers }, response }, next) => {
if (token) headers['Authorization'] = 'token ' + token;

await next();

if (method === 'POST' && path.startsWith('/session'))
token = response.headers.Token;
}
);

client.get('/path/to/your/API').then(console.log);

Up/Download files

(based on Iterable Observer)

import { request } from 'koajax';

document.querySelector('input[type="file"]').onchange = async ({
target: { files }
}) => {
for (const file of files) {
const { upload, download, response } = request({
method: 'POST',
path: '/files',
body: file,
responseType: 'json'
});

for await (const { loaded } of upload)
console.log(`Upload ${file.name} : ${(loaded / file.size) * 100}%`);

const { body } = await response;

console.log(`Upload ${file.name} : ${body.url}`);
}
};

Global Error fallback

npm install browser-unhandled-rejection
import { auto } from 'browser-unhandled-rejection';
import { HTTPError } from 'koajax';

auto();

self.addEventListener('unhandledrejection', event => {
if (!(event.reason instanceof URIError)) return;

const { message } = (event.reason as HTTPError).body;

if (!message) return;

event.preventDefault();

self.alert(message);
});

Read Files

(based on Iterable Observer)

import { readAs } from 'koajax';

document.querySelector('input[type="file"]').onchange = async ({
target: { files }
}) => {
for (const file of files) {
const { progress, result } = readAs(file, 'dataURL');

for await (const { loaded } of progress)
console.log(
`Loading ${file.name} : ${(loaded / file.size) * 100}%`
);

const URI = await result;

console.log(`Loaded ${file.name} : ${URI}`);
}
};

Generated using TypeDoc