relay-tools / react-relay-network-layer

ReactRelayNetworkLayer with middlewares and query batching for Relay Classic.
MIT License
277 stars 47 forks source link

Redirect to login page and network layer #51

Open CostaRico opened 7 years ago

CostaRico commented 7 years ago

I've tried to use network layer to redirect user to user page if status code is 401, but I dont know how to make redirect from callback:

import {
  RelayNetworkLayer,
  authMiddleware,
} from 'react-relay-network-layer';

Relay.injectNetworkLayer(new RelayNetworkLayer([

  authMiddleware({
    token: () => 'testtoken',
    tokenRefreshPromise(){
      // we are here if status code is 401
      // but how can I redirect user to login page here?
    }
  }),
]));

If I just remove token in tokenRefreshPromise and check it out in onEnter hook, user is able to open route because onEnter fires before tokenRefreshPromise.

What is the right way to redirect user to login page?

Thx a lot!

nodkz commented 7 years ago

If you want to show login window and freeze all queries until user will be logged in, do something like this:

tokenRefreshPromise = function() {
  return new Promise((resolve, reject) => {
    const afterLoginCallback = (err, token) => {
      if (err) reject(err);
      resolve(token);
    };

    // call some other method from your app which displays login form
    // and when user complete action will call `callback` which fulfill promise with token or error
    app.showLoginForm(afterLoginCallback);
  });
};

If you want just redirect and rejects all existed queries, use something like this:

tokenRefreshPromise = function() {
  window.location ='/login'; // force browser to reload page
  return Promise.reject('Authorization failed');
};

React-relay-network-layer leaves uncovered how you redirect or show login forms. Because in different clients (web browser, or native) this logic will be absolutely different. And I can not enforce some generic solution. So RRNL just provides Promise which you may resolve with token or reject as you wish.