Giter Site home page Giter Site logo

zcmgyu / redux-saga-api-call-routines Goto Github PK

View Code? Open in Web Editor NEW

This project forked from alvelig/redux-saga-api-call-routines

0.0 1.0 0.0 20 KB

redux-saga-api-call-routines is used to add authentication header to any \"*_REQUEST\" action. It is handy to use with redux-saga-routines.

JavaScript 100.00%

redux-saga-api-call-routines's Introduction

redux-saga-api-call-routines is used to add authentication header to any "*_REQUEST" action. It is handy to use with redux-saga-routines.

It also refreshes the token if 403 error is returned.

All pending requests are cancelled if cancelAll is dispatched.

Installation:

TODO: provide an npm version

Configuration:

import ApiCallSaga from 'redux-saga-api-call';

const predicate = (action) => {
  return action && _.endsWith(action.type, '_REQUEST') && action.payload && action.payload.url && action.payload.auth;
};

const api = { 
  /***
  * Promise
   * accepts payload from redux-saga-routine (expected url and fetch options)
   * returns fetch response with body resolved (ok and status must be present)
   * as they are conditions to detect success and rejected token responses
   * Maybe someday could make this conditions configurable...
  */
  fetchApi, //Promise - accepts payload from 
   /***
     * Promise
      * accepts refreshToken 
      * on success returns token, 
      * on token rejected returns null - in that case logout will be dispatched
      * other error throws error
     */
  refreshAccessToken 
};
const actions = { 
  logout, // logout action - if dispatched from somewhere else should trigger cancelAll 
  tokenRefreshing,  // set token is refreshing action 
  tokenRefreshed  // set token is refreshed action
};
const selectors = { 
  isTokenRefreshing, // is token refreshing now?
  selectAccessToken, // access token selector
  selectRefreshToken // refresh token selector
};

//
//your store and sagas configuration here
//
Saga.run([
  ... // <- other sagas here
  ApiCallSaga({
    predicate,
    ...api,
    ...actions,
    ...selectors,
  })
]);

fetchApi and refreshAccessToken could look like:

//TODO: set url from .env
const baseUrl = 'http://localhost/api/v1';

const opts = {
  defaultOptions: {
    method: 'GET',
  },
  defaultHeaders: {
    "Content-Type": "application/json"
  },
};

//TODO: catch anyway
export const fetchApi = ({ url, headers = {}, ...options }, token) => {
  return fetch(baseUrl + url, {
    ...opts.defaultOptions,
    ...options,
    headers: new Headers({
      ...opts.defaultHeaders,
      ...headers,
      'Authorization': `Bearer ${token}`
    })
  })
  //TODO: agree on response format
    .then(response => response.json().then(json => ({ ...response, json })))
    .catch(error => error);
};
//TODO: call refresh token, return token or error
export const refreshAccessToken = (refreshToken) => {
  return fetch(baseUrl + '/refresh', {
    method: 'GET',
    headers: new Headers({
      ...opts.defaultHeaders,
      'Authorization': `Bearer ${refreshToken}`
    })
  })
    .then(response => ({ token }))
    .catch(error => ({ error }));
};

redux-saga-api-call-routines's People

Contributors

alexander-veligurov avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.