Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@apicase/adapter-xhr

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@apicase/adapter-xhr

XHR adapter for apicase-core

  • 0.7.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4
decreased by-55.56%
Maintainers
1
Weekly downloads
 
Created
Source

@apicase/adapter-xhr

XHR adapter for @apicase/core

Installation

  1. Install via NPM
npm install @apicase/adapter-xhr
  1. Import it
import { apicase } from '@apicase/core'
import xhr from '@apicase/adapter-xhr'

const xhrAPI = apicase(xhr)

We use node-fetch as polyfill for Node.js

Basic usage

const req = await xhrAPI({
  url: '/api/posts',
  method: 'GET',
  headers: { token: 'my_secret_token' },
  query: { userId: 1 }
})

if (req.success) { 
  console.log(req.result)
} else {
  console.error(req.result)
}

It will call:

var xhr = new XMLHttpRequest()
xhr.open('GET', '/api/posts?userId=1', true)
xhr.onload = function onload (e) {
  // See validators
  if (isSuccess(e.target, e)) {
    console.log(e)
  } else {
    console.error(e)
  }
}
xhr.setRequestHeader('token', 'my_secret_token')
xhr.send(null)

Advanced

Url params

Fetch adapter also has path-to-regexp to pass urls params smarter. Params are stored in params property

xhrAPI({
  url: '/api/posts/:id',
  params: { id: 1 }
})
// => GET /api/posts/1

Dynamic headers

If you want to create dynamic headers object so you can pass headers property as function that returns headers object

xhrAPI({
  url: '/api/posts',
  method: 'POST',
  headers: () => ({
    token: localStorage.getItem('token')
  })
})

It will be called every time you make a request so if token will be removed, header won't be sent too.

Validator function

I've added possibility to customizate resolve/reject apicase requests with validator callback.
It accepts xhr target and onload event

xhrAPI({
  url: '/api/posts',
  validateStatus: (status) => 
    status >= 200 && status <= 299
})

Default validator function is here:

function defaultValidator (status) {
  return status >= 200 && status < 300
}

Author

Anton Kosykh

License

MIT

FAQs

Package last updated on 15 May 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc