Skip to content

Commit

Permalink
chore: Use fetch as default for browsers instead of reqwest (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
manueltanzi-okta authored Apr 15, 2019
1 parent 1128aba commit fddec0a
Show file tree
Hide file tree
Showing 16 changed files with 143 additions and 81 deletions.
4 changes: 2 additions & 2 deletions fetch/fetchRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ function fetchRequest(method, url, args) {
}
return result;
};
if (response.headers.get('Accept') &&
response.headers.get('Accept').toLowerCase().indexOf('application/json') >= 0) {
if (response.headers.get('Content-Type') &&
response.headers.get('Content-Type').toLowerCase().indexOf('application/json') >= 0) {
return response.json().then(respHandler);
} else {
return response.text().then(respHandler);
Expand Down
17 changes: 0 additions & 17 deletions fetch/index.js

This file was deleted.

20 changes: 20 additions & 0 deletions jest.browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var packageJson = require('./package.json');
var OktaAuth = '<rootDir>/' + packageJson.browser;

module.exports = {
'coverageDirectory': './build2/reports/coverage',
'restoreMocks': true,
'moduleNameMapper': {
'^OktaAuth(.*)$': OktaAuth
},
'testMatch': [
'**/test/spec/*.js'
],
'testPathIgnorePatterns': [
'./test/spec/serverStorage.js'
],
'reporters': [
'default',
'jest-junit'
]
};
18 changes: 0 additions & 18 deletions jest.browser.json

This file was deleted.

25 changes: 25 additions & 0 deletions jest.server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var packageJson = require('./package.json');
var OktaAuth = '<rootDir>/' + packageJson.main;

module.exports = {
'coverageDirectory': './build2/reports/coverage',
'restoreMocks': true,
'moduleNameMapper': {
'^OktaAuth(.*)$': OktaAuth
},
'testMatch': [
'**/test/spec/*.js'
],
'testPathIgnorePatterns': [
'./test/spec/fingerprint.js',
'./test/spec/general.js',
'./test/spec/oauthUtil.js',
'./test/spec/token.js',
'./test/spec/tokenManager.js',
'./test/spec/webfinger.js'
],
'reporters': [
'default',
'jest-junit'
]
};
17 changes: 0 additions & 17 deletions jest.server.json

This file was deleted.

6 changes: 4 additions & 2 deletions lib/browser/browserIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,7 @@
*
*/

// This exists to use reqwest for http requests by default when library used on browser
module.exports = require('../../reqwest');
var fetchRequest = require('../../fetch/fetchRequest');
var storageUtil = require('./browserStorage');

module.exports = require('./browser')(storageUtil, fetchRequest);
6 changes: 4 additions & 2 deletions lib/server/serverIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,7 @@
*
*/

// This exists to use fetch for http requests by default when library used on server side
module.exports = require('../../fetch');
var fetchRequest = require('../../fetch/fetchRequest');
var storageUtil = require('./serverStorage');

module.exports = require('./server')(storageUtil, fetchRequest);
7 changes: 6 additions & 1 deletion lib/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,12 @@ function getUserInfo(sdk, accessTokenObject) {
})
.fail(function(err) {
if (err.xhr && (err.xhr.status === 401 || err.xhr.status === 403)) {
var authenticateHeader = err.xhr.getResponseHeader('WWW-Authenticate');
var authenticateHeader;
if (err.xhr.headers && util.isFunction(err.xhr.headers.get) && err.xhr.headers.get('WWW-Authenticate')) {
authenticateHeader = err.xhr.headers.get('WWW-Authenticate');
} else if (util.isFunction(err.xhr.getResponseHeader)) {
authenticateHeader = err.xhr.getResponseHeader('WWW-Authenticate');
}
if (authenticateHeader) {
var errorMatches = authenticateHeader.match(/error="(.*?)"/) || [];
var errorDescriptionMatches = authenticateHeader.match(/error_description="(.*?)"/) || [];
Expand Down
4 changes: 4 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,7 @@ util.removeTrailingSlash = function(path) {
util.isIE11OrLess = function() {
return !!document.documentMode && document.documentMode <= 11;
};

util.isFunction = function(fn) {
return !!fn && {}.toString.call(fn) === '[object Function]';
};
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
"lint": "eslint .",
"lint:report": "eslint -f checkstyle -o build2/reports/lint/eslint-checkstyle-result.xml .",
"test": "yarn test:browser && yarn test:server",
"test:browser": "jest --config ./jest.browser.json",
"test:server": "jest --config ./jest.server.json",
"test:browser": "jest --config ./jest.browser.js",
"test:server": "jest --config ./jest.server.js",
"test:report": "yarn test --ci --silent || true",
"build": "node ./writeConfig.js && webpack --config webpack.config.js",
"prepublish": "yarn build"
Expand Down
2 changes: 2 additions & 0 deletions test/spec/fingerprint.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ var OktaAuth = require('OktaAuth');
var util = require('../util/util');
var packageJson = require('../../package.json');

jest.mock('cross-fetch');

describe('fingerprint', function() {
function setup(options) {
options = options || {};
Expand Down
2 changes: 2 additions & 0 deletions test/spec/oauthUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ var wellKnown = require('../xhr/well-known');
var keys = require('../xhr/keys');
var tokens = require('../util/tokens');

jest.mock('cross-fetch');

describe('getWellKnown', function() {
util.itMakesCorrectRequestResponse({
title: 'caches response and uses cache on subsequent requests',
Expand Down
2 changes: 2 additions & 0 deletions test/spec/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ var packageJson = require('../../package.json');
var _ = require('lodash');
var Q = require('q');

jest.mock('cross-fetch');

function setupSync() {
return new OktaAuth({ issuer: 'http://example.okta.com' });
}
Expand Down
46 changes: 46 additions & 0 deletions test/spec/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,50 @@ describe('util', function() {
});
});

describe('isFunction', function() {
it('returns false if argument is undefined', function() {
var fn;
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is null', function() {
var fn = null;
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is a boolean', function() {
var fn = true;
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is a number', function() {
var fn = 3;
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument a string', function() {
var fn = 'I am not a function!';
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is an Object', function() {
var fn = { name: 'Not a function!' };
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is a Date', function() {
var fn = new Date('December 17, 1995 03:24:00');
expect(util.isFunction(fn)).toBe(false);
});

it('returns false if argument is a RegExp', function() {
var fn = new RegExp('\\w+');
expect(util.isFunction(fn)).toBe(false);
});

it('returns true if argument is a function', function() {
var fn = function() { return 'I am a function!'; };
expect(util.isFunction(fn)).toBe(true);
});
});
});
44 changes: 24 additions & 20 deletions test/util/util.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* globals expect, JSON */
/* eslint-disable max-statements, complexity */
var Q = require('q'),
$ = require('jquery'),
_ = require('lodash'),
OktaAuth = require('OktaAuth'),
cookies = require('../../lib/browser/browserStorage').storage;
cookies = require('../../lib/browser/browserStorage').storage,
fetch = require('cross-fetch');

jest.mock('cross-fetch');

var util = {};

Expand Down Expand Up @@ -80,44 +82,46 @@ function mockAjax(pairs) {
setNextPair(pairs);
}

jest.spyOn($, 'ajax').mockImplementation(function(args) {

fetch.mockImplementation(function (url, args) {
var pair = allPairs.shift();
if (!pair) {
throw new Error('We are making a request that we have not anticipated.');
}

// Make sure every request is attaching cookies
expect(args.xhrFields).toEqual({
withCredentials: true
});
expect(args.credentials).toEqual('include');

if (pair.request) {
expect(pair.request.uri).toEqual(args.url);
if (pair.request.data || args.data) {
expect(pair.request.data).toEqual(JSON.parse(args.data));
expect(pair.request.uri).toEqual(url);
if (pair.request.data || args.body) {
expect(pair.request.data).toEqual(JSON.parse(args.body));
}
if (pair.request.headers) {
expect(pair.request.headers).toEqual(args.headers);
}
}

var deferred = $.Deferred();
var deferred = Q.defer();
var xhr = pair.response;

xhr.getResponseHeader = function(name) {
return xhr.headers && xhr.headers[name];
};
xhr.headers = xhr.headers || {};
xhr.headers['Content-Type'] = 'application/json';
xhr.headers.get = function(attr) {
return xhr.headers[attr];
}
xhr.ok = xhr.status >= 200 && xhr.status < 300;
xhr.json = function() {
return Q.Promise(function(resolve) {
resolve(xhr.responseText);
});
}

if (xhr.status > 0 && xhr.status < 300) {
// $.ajax send (data, textStatus, jqXHR) on success
_.defer(function () { deferred.resolve(xhr.response, null, xhr); });
_.defer(function () { deferred.resolve(xhr); });
} else {
// $.ajax send (jqXHR, textStatus, errorThrown) on failure
xhr.responseJSON = xhr.response;
deferred.reject(xhr, null, xhr.response);
deferred.reject(xhr);
}
return deferred;
return deferred.promise;
});

return {
Expand Down

0 comments on commit fddec0a

Please sign in to comment.