Socket
Socket
Sign inDemoInstall

@js-bits/loader

Package Overview
Dependencies
5
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @js-bits/loader

HTTP resource loader


Version published
Maintainers
1
Created

Readme

Source

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

Keywords

FAQs

Last updated on 13 Jun 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc