Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
@bmc/react-common / dist / aws / SecureApi.js
Size: Mime:
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import { extend, isFunction, get, cloneDeep } from 'lodash'; //TODO: - Add default error handling to secure fetch for unauthorized 401/403 calls to apis
// should redirect to login.

var default_options = {
  mode: "cors",
  // no-cors, cors, *same-origin
  cache: "no-cache",
  // *default, no-cache, reload, force-cache, only-if-cached
  credentials: "same-origin",
  // include, *same-origin, omit
  headers: {
    "Content-Type": "application/json; charset=utf-8" // "Content-Type": "application/x-www-form-urlencoded",

  },
  redirect: "follow",
  // manual, *follow, error
  referrer: "client" // no-referrer, *client

};

function secureFetch(url, auth, options) {
  return new Promise(
  /*#__PURE__*/
  function () {
    var _ref = _asyncToGenerator(
    /*#__PURE__*/
    _regeneratorRuntime.mark(function _callee(resolve, reject) {
      var _options, id_token;

      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _options = extend(cloneDeep(default_options), options);

              if ('onStart' in _options && isFunction(_options['onStart'])) {
                _options['onStart'].call();
              }

              if ('api_key' in _options) {
                _options['headers']['x-api-key'] = _options['api_key'];
              }

              if (!auth) {
                reject("auth property is undefined. You may need to wrap your component with the withAuth higher order component.");
              }

              _context.next = 6;
              return auth.getIdToken();

            case 6:
              id_token = _context.sent;
              _options['headers']['Authorization'] = 'Bearer ' + id_token;
              fetch(url, _options).then(function (response) {
                // response only can be ok in range of 2XX
                if (response.ok) {
                  // you can call response.json() here too if you want to return json
                  if ('onComplete' in _options && isFunction(_options['onComplete'])) {
                    _options['onComplete'].call();
                  }

                  resolve(response);
                } else {
                  //handle errors in the way you want to
                  switch (response.status) {
                    case 401:
                      auth.login();
                      break;

                    case 403:
                      console.log('Unauthorized for API: ' + url);
                      break;

                    case 404:
                      console.log('Object not found');
                      break;

                    case 500:
                      console.log('Internal server error');
                      break;

                    default:
                      console.log('Some error occurred');
                      break;
                  }

                  if ('onComplete' in _options && isFunction(_options['onComplete'])) {
                    _options['onComplete'].call();
                  }

                  reject(response);
                }
              }).catch(function (error) {
                //it will be invoked mostly for network errors
                //do what ever you want to do with error here
                console.error(error);

                if ('onComplete' in _options && isFunction(_options['onComplete'])) {
                  _options['onComplete'].call();
                }

                reject(error);
              });

            case 9:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }());
}

export function secureGet(url, auth, options) {
  var _options = extend({
    method: "GET"
  }, options);

  return secureFetch(url, auth, _options);
}
export function securePost(url, auth, data, options) {
  // body: JSON.stringify(data), // body data type must match "Content-Type" header
  var _options = extend({
    method: "POST"
  }, options);

  var contentType = get(_options, 'header.Content-Type', null) || 'application/json';

  if (contentType && contentType.indexOf('application/json') > -1) {
    _options['body'] = JSON.stringify(data);
  } else {
    _options['body'] = data;
  }

  return secureFetch(url, auth, _options);
}
export function securePut(url, auth, data, options) {
  var _options = extend({
    method: "PUT"
  }, options);

  var contentType = get(_options, 'header.Content-Type', null) || 'application/json';

  if (contentType && contentType.indexOf('application/json') > -1) {
    _options['body'] = JSON.stringify(data);
  } else {
    _options['body'] = data;
  }

  return secureFetch(url, auth, _options);
}
export function secureDel(url, auth, options) {
  var _options = extend({
    method: "DELETE"
  }, options);

  return secureFetch(url, auth, _options);
}
//# sourceMappingURL=SecureApi.js.map