@js-bits/loader
TypeScript icon, indicating that this package has built-in type declarations

1.0.8 • Public • Published

HTTP resource Loader

An implementation of Executor aimed to be used to load resources over HTTP. Built with Fetch API under the hood. Key features: automatic response type conversion; built-in timeout and abort capability; execution timings.

Installation

Install with npm:

npm install @js-bits/loader

Install with yarn:

yarn add @js-bits/loader

Import where you need it:

import Loader from '@js-bits/loader';

or require for CommonJS:

const Loader = require('@js-bits/loader');

How to use

Simple example

const swCharacter = new Loader('https://swapi.dev/api/people/1/');

(async () => {
  swCharacter.load(); // just a contextualized alias of Executor#execute();
  const result = await swCharacter;
  console.log(result.name); // Luke Skywalker
})();

Content type is automatically detected and the result type is based on that information. It can be one of the following:

  • Object - for 'application/json' content
  • String - for 'text/plain' content
  • HTMLDocument - for 'text/html' content
  • XMLDocument - for XML based content (like 'text/xml', and 'image/svg+xml')
  • Raw Response object when content type is not recognized

You can also explicitly specify expected content type using optional mimeType parameter.

const xml = new Loader('https://api.nbp.pl/api/exchangerates/tables/a/last/1/?format=xml', {
  mimeType: 'text/plain',
});

(async () => {
  xml.load();
  const result = await xml;
  console.log(result.slice(0, 38)); // <?xml version="1.0" encoding="utf-8"?>
})();

Since Loader is built with Fetch API you can pass fetch parameters the same way, using second argument.

const xml = new Loader(url, {
  method: 'POST',
  headers: {...}
  body: '...',
});

Additional features

There are Loader#send() and Loader#load() aliases of Executor#execute() method available for convenience. Also, unlike fetch(), Loader has built-in .abort() method.

Features of Executor, like execution timings and hard/soft timeout are also available here.

const url = 'https://www.bankofcanada.ca/valet/observations/group/FX_RATES_DAILY/xml?start_date=2021-05-30';
const content = new Loader(url, {
  timeout: 1000,
});
const { EXECUTED, RESOLVED } = Loader.STATES;

(async () => {
  content.load();

  try {
    const result = await content;
    const { timings } = content;
    console.log(result); // <data>...</data>
    console.log(`Load time: ${timings[RESOLVED] - timings[EXECUTED]} ms`); // Load time: 538 ms
  } catch (reason) {
    if (reason.name === Loader.TimeoutExceededError && reason.requestURL === url) {
      console.log('LoaderTimeoutError', reason.requestURL);
    }
  }
})();

Error handling

const content = new Loader('...');

(async () => {
  content.load();

  try {
    const result = await content;
    // ...
  } catch (reason) {
    switch (reason.name) {
      case Loader.RequestAbortError:
        // request has been aborted
        // ...
        break;
      case Loader.TimeoutExceededError:
        // request has exceeded specified timeout
        // ...
        break;
      case Loader.ResponseParsingError:
        // response was successfully received but something went wrong during parsing
        // you can use reason.response to get access to raw Response object
        // ...
        break;
      case Loader.RequestError:
        // error status code has received (4xx, 5xx)
        // ...
        break;
    }
  }
})();

Package Sidebar

Install

npm i @js-bits/loader

Weekly Downloads

3

Version

1.0.8

License

ISC

Unpacked Size

23.8 kB

Total Files

16

Last publish

Collaborators

  • apolo-gh