Based on a fetch.js, and allows creating a authenticated request to an api with oauth2 access_token. In addition to handling OAuth2 tokens it prevents race conditions between request when token needs to be generated or fetched.
npm install fetch-oauth2 --save
Storage takes 3 functions, and all of them are optional and must return a Promise, but you should pass in at least one of them it depends on the application.
import{tokenStorage}from'fetch-oauth2';conststorage=tokenStorage({initialToken, fetchToken, generateToken});fetchTokenis an equivalent to a httpGET, and canrejectthe promise when no token is foundgenerateTokenis an equivalent to a httpPOST, and should generate a new token
import{fetchWithMiddleware,middleware}from'fetch-oauth2';constoauth2Fetch=fetchWithMiddleware(middleware.authorisationChallengeHandler(storage),middleware.setOAuth2Authorization(storage));oauthFetch('http://httpbin.org/get').then(response=>/**/).catch(error=>/**/)Handles adding the Authorization: Bearer abc123 header to the request.
Handles responses with expired and invalid token's. When the response is 401, this hook will generate a new token and retry the request using the generated token.
You can optionally pass in a function that tests for the authentication challenge.
authorisationChallengeHandler(storage,(response)=>Response.resolve(true))Assuming that the api uri's are relative then its easy to add a simple middleware to add the host.
functionaddHostToUrl(next){returnconfigPromise=>{returnnext(configPromise.then(config=>config.updateUri(uri=>'http://httpbin.org'+uri)));}}constoauth2Fetch=fetchWithMiddleware(addHostToUrl, ...);oauth2Fetch('/get')The simplest why is to run test through npm.
npm test
If you would like to use wallaby.js then you need to start the test server.
npm start