Skip to content

determin1st/httpFetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

httpFetch

Individual fetch API wrapper for the browser (experimental, reactionary)

overview

The thing is pretty fast as it doesnt try to connect worlds, but rather lives in it's own native environment (the browser). So it will catch up with you faster than you may think.

HTTP request and response routine is super boring but standard procedure for all kinds of stuff.

While some folks having troubles with so called "native" apis, the best of us are using wrappers (self-made or other's libs - doesnt matter).

The thing is a kind of a wrapper, but armed with extra options and routes which may or may not happen with you during the HTTP request/response battle.

It's more advanced that any other tool which try to keep pace with the NODE's world because it uses (currently) experimental features of the browser. But it may be more aggressive in your environment - only modern syntax, only modern apis (but not the approach). As far as time flows, the previous statement becomes falsy.

So, the attempt of escaping your doom is futile: Face it one-to-one with the Spider Mastermind!

Spider Mastermind

Tests

  • Fail: check everything
  • Cancellation: cancel anything
  • Encryption: encrypt everything (FF only)
  • Retry: restart anything
  • Download: download anything
  • Upload: upload anything
  • Streams: stream something
  • Mix: mix everything

Try

ES5 script (classic)
<!-- CDN (stable) -->
<script src="https://cdn.jsdelivr.net/npm/http-fetch-json@2/httpFetch.js"></script>

<!-- GIT (lastest) -->
<script src="http://raw.githack.com/determin1st/httpFetch/master/httpFetch.js"></script>
ES6 module
// TODO
get the code
# GIT (lastest)
git clone https://github.com/determin1st/httpFetch

# NPM (stable)
npm i http-fetch-json

Syntax

httpFetch(options [, callback])

httpFetch(url, data [, callback])

httpFetch(url [, callback])

Parameters

Returns

Promise (no callback) or AbortController (callback)

Result handling

Optimistic style (the default)
async/await
var res = await httpFetch('/resource');
if (res instanceof Error)
{
  // FetchError
}
else if (!res)
{
  // JSON falsy values
}
else
{
  // success
}
promise
httpFetch('/resource')
  .then(function(res) {
    if (res instanceof Error)
    {
      // FetchError
    }
    else if (!res)
    {
      // JSON falsy values
    }
    else
    {
      // success
    }
  });
callback
httpFetch('/resource', function(ok, res) {
  if (ok && res)
  {
    // success
  }
  else if (!res)
  {
    // JSON falsy values
  }
  else
  {
    // FetchError
  }
});
Optimistic, when notNull (recommended)
custom instance
var oFetch = httpFetch.create({
  notNull: true
});
async/await
var res = await oFetch('/resource');
if (res instanceof Error)
{
  // FetchError
}
else
{
  // success
}
promise
oFetch('/resource')
  .then(function(res) {
    if (res instanceof Error)
    {
      // FetchError
    }
    else
    {
      // success
    }
  });
callback
oFetch('resource', function(ok, res) {
  if (ok)
  {
    // success
  }
  else
  {
    // FetchError
  }
});
Pessimistic style, when promiseReject
custom instance
var pFetch = httpFetch.create({
  promiseReject: true
});
async/await
try
{
  var res = await pFetch('/resource');
  if (res)
  {
    // success
  }
  else
  {
    // JSON falsy values
  }
}
catch (err)
{
  // FetchError
}
promise
oFetch('/resource')
  .then(function(res) {
    if (res)
    {
      // success
    }
    else
    {
      // JSON falsy values
    }
  })
  .catch(function(err)
  {
    // FetchError
  });
Pessimistic, when promiseReject and notNull
custom instance
var pFetch = httpFetch.create({
  notNull: true,
  promiseReject: true
});
async/await
try
{
  var res = await pFetch('/resource');// success
}
catch (err)
{
  // FetchError
}
promise
oFetch('/resource')
  .then(function(res) {
    // success
  })
  .catch(function(err)
  {
    // FetchError
  });

Result types

FetchError

error categories
if (res instanceof Error)
{
  switch (res.id)
  {
    case 0:
      ///
      // connection problems:
      // - connection timed out
      // - wrong CORS headers
      // - unsuccessful HTTP STATUSes (not in 200-299 range)
      // - readable stream failed
      // - etc
      ///
      console.log(res.message);   // error details
      console.log(res.response);  // request + response data, full house
      break;
    case 1:
      ///
      // something's wrong with the response data:
      // - empty response
      // - incorrect content type
      // - etc
      ///
      break;
    case 2:
      ///
      // security compromised
      ///
      break;
    case 3:
      ///
      // incorrect API usage
      // - wrong syntax used
      // - something's wrong with the request data
      // - internal bug
      ///
      break;
    case 4:
      ///
      // aborted programmatically:
      // - canceled parsing, before the request was made
      // - canceled fetching, before the response arrived
      // - canceled parsing, after the response arrived
      // - stream canceled
      ///
      break;
    case 5:
      ///
      // unclassified
      ///
      break;
  }
}

Advanced

httpFetch.create

httpFetch.create(config)

Parameters

  • config - an object with instance options

base
name type default description
baseUrl string ``
mounted boolean false

Description

Creates a new instance of of httpFetch

Examples

var a = httpFetch.create();
var b = a.create();

if ((a instanceof httpFetch) &&
    (b instanceof httpFetch))
{
  // true!
}
httpFetch.cancel

httpFetch.cancel()

Description

Cancels all running fetches of the instance

httpFetch.form

httpFetch.form(url, data[, callback(ok, res)])

httpFetch.form(options[, callback(ok, res)])

Description

httpFetch operates with JSON content by default. This shortcut method allows to send a POST request with body conforming to one of the form enctypes:

Parameters

Same as httpFetch

Examples

// CLIENT (JS)
// let's send a plain content without files,
// there is no need in FormData format, so
// it will be automaticly detected as
// x-www-form-urlencoded:
res = httpFetch.form(url, {
  param1: 1,
  param2: 2,
  param3: 3
});
# SERVER (PHP)
# get parameters and calculate their sum:
$sum = $_POST['param1'] + $_POST['param2'] + $_POST['param3'];
# respond with JSON
echo json_encode($sum);
# and quit
exit;
// CLIENT (JS)
// wait for the response and display it:
console.log(await res);// 6
// CLIENT (JS)
// let's send another request with file attached,
// the body will be sent as
// multipart/form-data:
res = await httpFetch.form(url, {
  param1: 1,
  param2: 2,
  param3: 3,
  fileInput: document.querySelector('input[type="file"]')
});
// SERVER's $_FILES will be populated with uploaded file,
// but the response/result will be the same:
console.log(res);// 6

KISS API

overview

What exactly is the REST API? In a nutshell, it's only a collection of endpoints:

Endpoints are important aspects of interacting with server-side web APIs, as they specify where resources lie that can be accessed by third party software. Usually the access is via a URI to which HTTP requests are posted, and from which the response is thus expected.

The original definition of the REST does not restrict or explicitly specify certain HTTP methods to use with, there is no CRUD in there. Check the link and try to find it, if you doubt.

Still, some dumb dumbies are unable to differentiate the origin and the mutatated forms of the term, but thats not the reason why KISS word is used.

The KISS (Keep It Simple Stupid) is how the REST is implemented.

What is AJAX then? Well, thats also an implementation of the REST (or a subset). It is bound to the JavaScript, XML and XMLHttpRequest. Generally, you say that jQuery, axios, superagent or other lib is AJAX if it utilizes XMLHttpRequest api. ...

What about RPC? ...

how

use POST method

// instead of GET method, you may POST:
res = await httpFetch(url, {});       // EMPTY OBJECT
res = await httpFetch(url, undefined);// EMPTY BODY
res = await httpFetch(url, null);     // JSON NULL
// it may easily expand to
// into list filters:
res = await httpFetch(url, {
  categories: ['one', 'two'],
  flag: true
});
// or item extras:
res = await httpFetch(url, {
  fullDescription: true,
  ownerInfo: true
});
// OTHERWISE,
// parametrized GET will swamp into:
res = await httpFetch(url+'?flags=123&names=one,two&isPulluted=true');

// DO NOT use multiple/mixed notations:
res = await httpFetch(url+'?more=params', params);
res = await httpFetch(url+'/more/params', params);
// DO unified:
res = await httpFetch(url, Object.assign(params, {more: "params"}));

// by default,
// any HTTP status, except 200 is a FetchError:
if (res instanceof Error) {
  console.log(res.status);
}
else {
  console.log(res.status);// 200
}

Links

https://javascript.info/fetch-api

https://tom.preston-werner.com/2010/08/23/readme-driven-development.html

https://code.tutsplus.com/tutorials/why-youre-a-bad-php-programmer--net-18384


<style type="text/css"> summary {font-size:1.2em;font-weight:bold;color:skyblue;} </style>