HTTP Provider with integrated auth tokens
Based on fetch.
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"
First you need to create a factory
const factory = AuthHTTPProvider.make({ getToken, saveToken, refreshToken, onError })
Options:
getToken
–void => Promise<string>
– returns saved auth tokensaveToken
–token => Promise<void>
– save refreshed tokenrefreshToken
–() => Promise<string>
– refresh current tokenonError
–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/json
header)form
–FormData
– FormData object to be passed as a request bodyheaders
–object
– any additional headers
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.
- 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.