0.1.3 • Published 7 years ago

fetch-json-simple v0.1.3

Weekly downloads
21
License
-
Repository
github
Last release
7 years ago

fetch-json-simple

Configurable wrapper around fetch to retrieve JSON

Main features:

  • Attaches relevant headers for JSON:
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  • Stringifies request { body } (but can also handle already stringified body)
  • Text responses converted to JSON { body }
  • Options are merged rather than assigned.
  • Auto-specifies {method: 'post'} if omitted and a body was passed
  • Shortcut methods: fetch.get, fetch.post, fetch.put, ...

Additional features:

  • Configurable fetch - use either native or polyfill
  • Configurable host - prefixed to paths before sending request
  • ... see #config

Other similar libraries: json-fetch, fetch-json.

Install

npm install fetch-json-simple --save

Usage

Example

fetch('/data-path')
  .then(json => {
    if (json.body) {
      // text body
    } else {
      // json
    }
  }).catch(error => {

  })

API

fetch(path, options)
  • path [string](required) Path to make request to.

  • options [object] Options object containing headers, body etc. body can be plain JS object.

    Merged with configured options object (see #config) and the following json-related default options object:

    defaults = {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    }
      merge({},
        defaults, // above
        {method: body ? 'post' : 'get'},
        fetch.options, // configured
        opts, // passed as argument
        {body} // after stringifying
      )

Shortcut Methods

fetch.⟪method⟫(...)
  • get Equivalent of: fetch(path, {method: 'get'})
  • post Equivalent of: fetch(path, {method: 'post'})
  • ... put, patch, delete

Config

fetch.⟪config⟫ = ...
  • host [string](default:none) Use this host to add all paths to before making the fetch request

    fetch.host = 'http://server.com'
  • options [object](default:none) Default set of options used in every fetch request. Merged with actual (json-related) options.

    fetch.options = {
      headers: {
        'Cache-Control': 'no-cache'
        // 'Accept': 'application/json',  < will still be present in final request
        'Content-Type': 'json' // < overridden default json-related option
    
      }
    }
  • fetch [function](default:none(uses native)) Underlying fetch function to use. Use this to polyfill if needed.

    fetch.fetch = require('isomorphic-fetch')

    You may also use isomorphic-fetch to globally polyfill the underlying fetch in which case the above won't be needed.

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago