honoka
TypeScript icon, indicating that this package has built-in type declarations

0.5.2 • Public • Published

honoka

npm version Build Status Coverage Status

Just a fetch() API wrapper for both Browser and Node.js.

Features

  • Same as fetch() API
  • Timeout
  • Interceptors before request and response
  • Transform/convert request and response

Installing

Using npm:

$ npm install honoka

Using cdn:

<script src="https://unpkg.com/honoka/lib/honoka.min.js"></script>

Example

Performing a GET request

// Make a request for a user with a given ID
honoka.get('/user?ID=12345')
  .then(response => {
    console.log(response);
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
 
// Optionally the request above could also be done as
honoka.get('/user', {
    data: {
      ID: 12345
    }
  })
  .then(response => {
    console.log(response);
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

Performing a POST request

honoka.post('/user', {
    data: {
      firstName: 'Fred',
      lastName: 'Flintstone'
    }
  })
  .then(response => {
    console.log(response);
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

honoka API

Requests can be made by passing the relevant config to honoka.

honoka(options)
// Send a POST request
honoka('/user/12345', {
  method: 'post',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
honoka(url[, options])
// Send a GET request (default method)
honoka('/user/12345');

Request method aliases

For convenience aliases have been provided for all supported request methods.

honoka.get(url[, options])
honoka.delete(url[, options])
honoka.head(url[, options])
honoka.options(url[, options])
honoka.post(url[, options])
honoka.put(url[, options])
honoka.patch(url[, options])

Request Config

These are the available config options for making requests. Same as fetch() API.

{
  // `method` is the request method to be used when making the request
  method: 'get', // default
 
  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},
 
  // `data` are the URL parameters or post body to be sent
  data: {
    ID: 12345
  },
 
  // `baseURL` will be prepended to `url` unless `url` is absolute.
  baseURL: 'https://some-domain.com/api/',
 
  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000,
 
  // `dataType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'buffer', 'json', 'text', 'auto'
  dataType: 'auto', // default
 
  // Authentication credentials mode
  // https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
  credentials: 'omit', // default
 
 
  // `expectedStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `expectedStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  expectedStatus(status) {
    return status >= 200 && status < 400; // default
  },
 
  // to ignore interceptors for one request
  ignoreInterceptors: false,
}

Config Defaults

You can specify config defaults that will be applied to every request.

Global Defaults

honoka.defaults.baseURL = 'https://example.com/api';
honoka.defaults.timeout = 10e3;
honoka.defaults.method = 'get';
honoka.defaults.headers.post['Content-Type'] = 'application/json';

Interceptors

You can intercept requests or responses before they are handled by then.

const unregister = honoka.interceptors.register({
  request: options => {
    // Modify the options here
    const token = localStorage.getItem('token');
    if (token) {
      options.headers['X-JWT-Token'] = token;
    }
    return options;
  },
  response: response => {
    // Check responseData here
    if (response.data.status && response.data.status !== 'success') {
      return new Error(response.data.message);
    }
    // Modify the response object
    return response;
  }
})
 
// Unregister your interceptor
unregister();

Abort Operation

You can cancel a pending request manually by using AbortController.

let abortController = new AbortController(),
    signal = abortController.signal;
 
honoka('/100MBtest.bin', { signal })
  .then((res) => {
    console.log(res)
  })
  .catch((err) => {
    console.log(err);
  });
 
setTimeout(() => {
  abortController.abort();
}, 2000);

Promises

honoka depends on a native ES6 Promise implementation to be supported.
If your environment doesn't support ES6 Promises, you can polyfill.

TypeScript

honoka includes TypeScript definitions.

import honoka from 'honoka';
honoka.get('/user?ID=12345');

Changelog

For changelogs, see Release Notes.

License

MIT

Package Sidebar

Install

npm i honoka

Weekly Downloads

18

Version

0.5.2

License

MIT

Unpacked Size

121 kB

Total Files

8

Last publish

Collaborators

  • kokororin