HTTP Provider with integrated auth tokens
Based on fetch.
npm i @cadolabs/auth-http-provideror
yarn add @cadolabs/auth-http-providerAnd require it for further usage
import AuthHTTPProvider from "@cadolabs/auth-http-provider"First you need to create a factory
const factory = AuthHTTPProvider.make({ getAccessToken, saveTokens, refreshTokens, onError })Options:
getAccessToken–() => Promise<string>– returns saved access tokensaveTokens–(tokens: { accessToken: string, refreshToken: string }) => Promise<void>– save tokensrefreshTokens–() => Promise<{ accessToken: string, refreshToken: string }>– refresh current tokensonError–Error => void– calls on error (Error object is just a request fromfetch)
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:
baseURL–string– base url of API server (eg.https://api.example.com/v1)
Request options:
query–object– object to be used in url as query paramsjson–object– object to be passed as a request body (also addsContent-Type: application/jsonheader)form–FormData– FormData object to be passed as a request bodyheaders–object– any additional headers
On each request performing it calls callback getAccessToken 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 tokens using callback refreshTokens and perform it one more time with the new access token. If it fails again, it calls onError callback and throws an error.
If request complited successfully with new token, it calls saveTokens to make your code save new tokens somewhere.
In other cases it behaves like a regular request-performing library.
- 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
Released under MIT License.