Giter Club home page Giter Club logo

nano-request's Introduction

Nano Request

A tiny promise wrapper around xmlHttpRequest ...

Signature

/**
 * Check if value is undefined
 *
 * @param {Object} value
 * @returns {boolean} true if undefined, false if not
 */

function isUndefined(val) {
  return typeof val === 'undefined'
}

/**
 * @param  {} options
 * @param  {} timeout
 * @todo: add timeout specific to cancel the request
 *
 * @returns promise over xmlhttprequest
 */

function nanoRequest(options, timeout) {
  if (!options) {
    /*
{
  method: String,
  url: String,
  headers: String | Object
  params: Object
}
*/
    options = {
      method: 'GET',
      url: 'https://swapi.dev/api/people/1/',
      params: {},
      headers: {},
    }
  }

  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest()
    const params = options.params

    xhr.open(options.method, options.url, true)

    xhr.onload = function () {
      if (this.status >= 200 && this.status < 400) {
        resolve(xhr.response)
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText,
        })
      }
    }

    xhr.onerror = function () {
      setTimeout(function () {
        reject(new TypeError('Request failed'))
      }, 0)
    }

    xhr.ontimeout = function () {
      setTimeout(function () {
        reject(new TypeError('Request timed-out'))
      }, 0)
    }

    xhr.onabort = function () {
      setTimeout(function () {
        reject(new TypeError('Request aborted'))
      }, 0)
    }

    if (options.headers) {
      Object.keys(opts.headers).forEach(function (name) {
        xhr.setRequestHeader(name, opts.headers[name])
      })
    }

    if (params && typeof params === 'object') {
      params = Object.keys(params)
        .map(function (key) {
          return encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
        })
        .join('&')
    }

    xhr.send(params)
  })
}

Usage

// a. promise
nanoRequest({
  method: 'GET',
  url: 'https://swapi.dev/api/people/1/',
})
  .then(function (data) {
    console.log(data)
  })
  .catch(function (error) {
    console.error('Uggh, there was an error!', error.status)
  })

// b. async / await
async function fetchData() {
  try {
    const response = await nanoRequest({method: 'GET', url: 'https://swapi.dev/api/people/1/'})
  } catch(error) {
      console.error('Uggh, there was an error!', err.status)
  }

nano-request's People

Contributors

ahadb avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.