Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the network layer in Relay

Tags:

graphql

relay

I know relay can inject a network layer when bootstrapping like below:

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('http://example.com/graphql', {
    headers: {
      Authorization: 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ==',
    },
  })
);

But how about if I need to tell what the header is later(like after signing in)?

like image 384
Ron Avatar asked Jan 05 '23 22:01

Ron


2 Answers

I found a simple trick. You can pass in headers object and update its pointer value.

const headers = {
    Authorization: '',
};

Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('http://example.com/graphql', {
    headers: headers,
  })
);

// To update the authorization, set the field.

headers.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ=='
like image 57
massanishi Avatar answered Feb 16 '23 21:02

massanishi


Great question. I imagine you're setting the network layer in your base component file. You could create a function wrapping the Relay.injectNetworkLayer call that updates the Auth header when you need to.

When loading the app, you could do something like this:

export function setNetworkLayer() {
  return new Promise((resolve, reject) => {

      var options = {};
      if (localStorage.authToken) {
        options.headers = {
          Authorization: 'Basic ' + localStorage.authToken
        }
      }
      else {
        options.headers = {};
      }
      Relay.injectNetworkLayer(
        new Relay.DefaultNetworkLayer('http://example.com/graphql', options)
      );
      resolve(options);
    });
  })
}

And if you wanted to update the network layer, you'd do something like this:

loginUser().then((res) => {
    localStorage.authToken = res.token;
    setNetworkLayer();
    return;
})
like image 44
vince Avatar answered Feb 16 '23 22:02

vince