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

koajax

v3.0.3

Published

HTTP Client based on Koa-like middlewares

Downloads

488

Readme

KoAJAX

HTTP Client based on Koa-like middlewares

NPM Dependency CI & CD

NPM

Feature

Request Body

Automatic Serialized types:

  1. Pure text: string
  2. Form encoding: URLSearchParams, FormData
  3. DOM object: Node
  4. JSON object: Object
  5. Binary data: Blob, ArrayBuffer, TypedArray, DataView
  6. Stream object: ReadableStream

Response Body

Automatic Parsed type:

  1. HTML/XML: Document
  2. JSON: Object
  3. Binary data: ArrayBuffer

Usage

Browser

Installation

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>
    <script src="https://polyfill.web-cell.dev/feature/TextEncoder.js"></script>
    <script src="https://polyfill.web-cell.dev/feature/AbortController.js"></script>
    <script src="https://polyfill.web-cell.dev/feature/Stream.js"></script>
</head>

Node.js

Installation

npm install koajax jsdom

index.ts

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);
});

Execution

npx tsx index.ts

Non-polyfillable runtimes

  1. https://github.com/idea2app/KoAJAX-Taro-adapter

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

Single HTTP request based on XMLHTTPRequest progress events

(based on Async Generator)

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}`);
    }
};

Multiple HTTP requests based on Range header

npm i native-file-system-adapter  # Web standard API polyfill
import { showSaveFilePicker } from 'native-file-system-adapter';
import { HTTPClient } from 'koajax';

const bufferClient = new HTTPClient({ responseType: 'arraybuffer' });

document.querySelector('#download').onclick = async () => {
    const fileURL = 'https://your.server/with/Range/header/supported/file.zip';
    const suggestedName = new URL(fileURL).pathname.split('/').pop();

    const fileHandle = await showSaveFilePicker({ suggestedName });
    const writer = await fileHandle.createWritable(),
        stream = bufferClient.download(fileURL);

    try {
        for await (const { total, loaded, percent, buffer } of stream) {
            await writer.write(buffer);

            console.table({ total, loaded, percent });
        }
        window.alert(`File ${fileHandle.name} downloaded successfully!`);
    } finally {
        await writer.close();
    }
};

Global Error fallback

npm install browser-unhandled-rejection  # Web standard API polyfill
import { auto } from 'browser-unhandled-rejection';
import { HTTPError } from 'koajax';

auto();

window.addEventListener('unhandledrejection', ({ reason }) => {
    if (!(reason instanceof HTTPError)) return;

    const { message } = reason.response.body;

    if (message) window.alert(message);
});

Read Files

(based on Async Generator)

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}`);
    }
};