typicode/fetchival

Support custom headers

Closed this issue · 4 comments

Currently, the request headers are fixed by:

opts.headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

It would be nice to support extra/custom headers. For example:

opts.headers = Object.assign({}, {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}, opts.headers);

This would support overridding the default headers, but Object.assign would need to be polyfilled in a lot of browsers.

What do you think?

Hmm, seems great except for the polyfilled part.
I don't see what other headers could be added? Do you have any examples?

Custom headers prefixed with X-, for example: X-Access-Token. Or if you need to POST with a different Content-Type, like application/x-www-form-urlencoded.

You're right.
Working on something.

It took a little time, but here it is in v0.2.0.
You can pass fetch options as a second argument to fetchival()

var request = fetchival('/', {
  // fetch options
  headers: {
    'X-SOME-HEADER': 'foo'
  }
})

// subsequent call to request will inherit previous fetch options
var posts = request('posts')

// you can add other options too
// will have X-SOME-HEADER and be in CORS mode
var users = request('users', { mode: 'cors' }) 

fetchival() signature has changed also:

fetchival('posts', 1, 'comments') // KO in v0.2.0
fetchival('posts/' + 1 + '/comments') // OK