relay-tools / react-relay-network-layer

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

how to update jwt in authMiddleware ? #29

Closed atteia closed 7 years ago

atteia commented 7 years ago

Hello,

I use react-native and rnrf-relay-renderer with Relay

The networkLayer works fine if I closed the App and reopen it after sign in but if new user for the app do sign in and redirected to home screen the token not updated and can't execute any queries

My layer code

import Config from './Config';
import LocalStore from 'react-native-simple-store';

import Relay from 'react-relay';
import {
  RelayNetworkLayer, retryMiddleware, urlMiddleware, authMiddleware, loggerMiddleware,
  perfMiddleware, gqErrorsMiddleware
} from 'react-relay-network-layer';

let mytoken = undefined;
 LocalStore.get('LoginData').then((User)=>{
   mytoken = User.authToken
 });

Relay.injectNetworkLayer(new RelayNetworkLayer([
  urlMiddleware({
    url: (req) => Config.GRAPHQL,
  }),
  loggerMiddleware(),
  gqErrorsMiddleware(),
  perfMiddleware(),
  retryMiddleware({
    fetchTimeout: 15000,
    retryDelays: (attempt) => [3200, 6400, 12800, 25600, 51200, 102400, 204800, 409600],
    statusCodes: [500, 503, 504]
  }),
  authMiddleware({
    token: () => mytoken
  }),

], { disableBatchQuery: true }));

could you help me to update token when sign in or sign out ?

nodkz commented 7 years ago

Sure, you provided all that is needed

Try following code:

import Config from './Config';
import LocalStore from 'react-native-simple-store';

import Relay from 'react-relay';
import {
  RelayNetworkLayer, retryMiddleware, urlMiddleware, authMiddleware, loggerMiddleware,
  perfMiddleware, gqErrorsMiddleware
} from 'react-relay-network-layer';

Relay.injectNetworkLayer(new RelayNetworkLayer([
  urlMiddleware({
    url: (req) => Config.GRAPHQL,
  }),
  loggerMiddleware(),
  gqErrorsMiddleware(),
  perfMiddleware(),
  retryMiddleware({
    fetchTimeout: 15000,
    retryDelays: (attempt) => [3200, 6400, 12800, 25600, 51200, 102400, 204800, 409600],
    statusCodes: [500, 503, 504]
  }),
  authMiddleware({
    token: () => LocalStore.get('LoginData').then(User => User.authToken),
  }),

], { disableBatchQuery: true }));

authMiddleware should resolve promise from LocalStore and after that send a request. It will do this for every request.

atteia commented 7 years ago

many thanks for you it works fine 👍