Skip to content

Cookbook: manipulate requests

Eugene Lazutkin edited this page Nov 26, 2019 · 5 revisions

This is part of the main module. See main for the full documentation.

"Virtual" hosts

Create "virtual" hosts so we can refer to them without knowing actual domain names. They can be substituted dynamically, or even calculated on-the-fly:

const redirects = {
  $api: window.API_HOST,
  $assets: window.ASSETS_HOST,
  $auth: window.AUTH_HOST
};
const redirectSources = Object.keys(redirects);

const prevProcessOptions = io.processOptions;
io.processOptions = options => {
  options = prevProcessOptions(options);

  for (let i = 0; i < redirectSources.length; ++i) {
    const redirect = redirectSources[i];
    if (redirect.length && options.url.substr(0, redirect.length) === redirect
        && options.url.charAt(redirect.length) === '/') {
      const newOptions = Object.create(options);
      newOptions.url = redirects[redirect] +
        newOptions.url.substr(redirect.length);
      return newOptions;
    }
  }

  return options;
};

Now we can access our hosts in different environments:

const thing = await io.get('$api/things/1');
await io.patch(`$assets/${thing.assetId}`, {text: 'a toy'});
io.cache.remove('$auth/*');

Add authentication headers

This is a realistic example that uses OAuth2:

// to be populated later:
let oauth2Tokens = null;

// hosts controlled by oauth2Tokens
const remoteHosts = [
  'https://api.example.com/',
  'https://assets.example.com/',
  'https://auth.example.com/',
  'http://localhost:3000/'
];

const prevProcessOptions = io.processOptions;
io.processOptions = options => {
  options = prevProcessOptions(options);
  if (oauth2Tokens) {
    for (let i = 0; i < remoteHosts.length; ++i) {
      const remoteHost = remoteHosts[i];
      if (remoteHost.length && options.url.substr(0, remoteHost.length) ===
          remoteHost) {
        const newOptions = Object.create(options);
        newOptions.headers = newOptions.headers ? {...newOptions.headers} : {};
        if (!newOptions.headers.Authorization) {
          newOptions.headers.Authorization = oauth2Tokens.id_token;
        }
        return newOptions;
      }
    }
  }
  return options;
};
Clone this wiki locally