Skip to content

Cado-Labs/auth-http-provider

Repository files navigation

@cadolabs/auth-http-provider · Supported by Cado Labs

CI npm version Coverage Status

HTTP Provider with integrated auth tokens

Based on fetch.

Install

npm i @cadolabs/auth-http-provider

or

yarn add @cadolabs/auth-http-provider

And require it for further usage

import AuthHTTPProvider from "@cadolabs/auth-http-provider"

Usage

First you need to create a factory

const factory = AuthHTTPProvider.make({ getToken, saveToken, refreshToken, onError })

Options:

  • getTokenvoid => Promise<string> – returns saved auth token
  • saveTokentoken => Promise<void> – save refreshed token
  • refreshToken() => Promise<string> – refresh current token
  • onErrorError => void – calls on error (Error object is just a request from fetch)

And after that you can create a http provider:

const provider = factory.create({ baseURL })

await provider.get("/some-url", { query, headers })
await provider.post("/some-url", { json, headers })
await provider.put("/some-url", { json, headers })
await provider.patch("/some-url", { json, headers })
await provider.delete("/some-url", { json, headers })

Options:

  • baseURLstring – base url of API server (eg. https://api.example.com/v1)

Request options:

  • queryobject – object to be used in url as query params
  • jsonobject – object to be passed as a request body (also adds Content-Type: application/json header)
  • formFormData – FormData object to be passed as a request body
  • headersobject – any additional headers

How does it work

On each request performing it calls callback getToken to get the auth token and makes the request with auth header Authorization: Bearer <token>.

When any request you made fails with 401 error code, it tries to refresh the token using callback refreshToken and perform it one more time with the new token. If it fails again, it calls onError callback and throws an error.

If request complited successfully with new token, it calls saveToken to make your code save it somewhere.

In other cases it behaves like a regular request-performing library.

Contributing

  • Fork it ( https://github.com/Cado-Labs/auth-http-provider )
  • Create your feature branch (git checkout -b feature/my-new-feature)
  • Commit your changes (git commit -am '[feature_context] Add some feature')
  • Push to the branch (git push origin feature/my-new-feature)
  • Create new Pull Request

License

Released under MIT License.

Supporting

Supported by Cado Labs

Authors

Aleksei Bespalov