Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Use fetch as default for browsers instead of reqwest #199

Merged
merged 8 commits into from
Apr 15, 2019
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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') &&
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Corrected, should be Content-Type in response.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤦‍♂️

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Double checking - now that we're using cross-fetch in our tests, are we able to catch this error?

Also, did notice that we're not mocking out the response.text() function here - do we need to? In general, when will be have a response that's not application/json?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, now we are able to catch that!

fyi, response.text() was working properly anyway for our flow, since we always do a JSON.parse in http https://github.com/okta/okta-auth-js/blob/master/lib/http.js#L60, this is why I haven't notice that during manual testing.

For what I have seen all our response should be application/json, so maybe should I remove the if/else?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems reasonable if we're catching it downstream. Would also be curious why we have that code to handle it in the first place - my hunch is that at some point we'd occasionally return an error that was not a json response. This might be fixed now though.

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
21 changes: 21 additions & 0 deletions test/spec/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,25 @@ 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 not a function', function() {
var fn = "I am not a function!";
expect(util.isFunction(fn)).toBe(false);
haishengwu-okta marked this conversation as resolved.
Show resolved Hide resolved
});

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();
haishengwu-okta marked this conversation as resolved.
Show resolved Hide resolved
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) {
haishengwu-okta marked this conversation as resolved.
Show resolved Hide resolved
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