optimized lib size - changed frontexpress.Middleware now it returns a class and not an instance anymore

This commit is contained in:
Camel Aissani 2017-01-13 14:23:15 +01:00
parent 465c53cd4f
commit 02b3fc1edb
18 changed files with 506 additions and 667 deletions

View File

@ -6,4 +6,4 @@ before_script:
- npm install coveralls - npm install coveralls
after_script: after_script:
- cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js - cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js

View File

@ -1,15 +1,14 @@
(function (global, factory) { var frontexpress = (function () {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 'use strict';
typeof define === 'function' && define.amd ? define(factory) :
(global.frontexpress = factory());
}(this, (function () { 'use strict';
/** /**
* HTTP method list * HTTP method list
* @private * @private
*/ */
var HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH']; var HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];
// not supported yet
// HEAD', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH';
var classCallCheck = function (instance, Constructor) { var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
@ -59,29 +58,45 @@ var createClass = function () {
var set$1 = function set$1(object, property, value, receiver) {
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent !== null) { var slicedToArray = function () {
set$1(parent, property, value, receiver); function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
} }
} else if ("value" in desc && desc.writable) {
desc.value = value;
} else {
var setter = desc.set;
if (setter !== undefined) { return _arr;
setter.call(receiver, value);
}
} }
return value; return function (arr, i) {
}; if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
@ -129,25 +144,33 @@ var Requester = function () {
*/ */
value: function fetch(request, resolve, reject) { value: function fetch(request, resolve, reject) {
var _this = this; var method = request.method,
uri = request.uri,
var method = request.method; headers = request.headers,
var uri = request.uri; data = request.data;
var headers = request.headers;
var data = request.data;
var success = function success(responseText) { var success = function success(responseText) {
resolve(request, { status: 200, statusText: 'OK', responseText: responseText }); resolve(request, {
status: 200,
statusText: 'OK',
responseText: responseText
});
}; };
var fail = function fail(_ref) { var fail = function fail(_ref) {
var status = _ref.status; var status = _ref.status,
var statusText = _ref.statusText; statusText = _ref.statusText,
var errorThrown = _ref.errorThrown; errorThrown = _ref.errorThrown;
var errors = _this._analyzeErrors({ status: status, statusText: statusText, errorThrown: errorThrown }); // Removed for reducing size of frontexpress
reject(request, { status: status, statusText: statusText, errorThrown: errorThrown, errors: errors }); // const errors = this._analyzeErrors({status, statusText, errorThrown});
reject(request, {
status: status,
statusText: statusText,
errorThrown: errorThrown,
errors: 'HTTP ' + status + ' ' + (statusText ? statusText : '')
});
}; };
var xmlhttp = new XMLHttpRequest(); var xmlhttp = new XMLHttpRequest();
@ -198,47 +221,47 @@ var Requester = function () {
} }
} }
/** // Removed for reducing size of frontexpress
* Analyse response errors. // /**
* // * Analyse response errors.
* @private // *
*/ // * @private
// */
}, { // _analyzeErrors(response) {
key: '_analyzeErrors', // // manage exceptions
value: function _analyzeErrors(response) { // if (response.errorThrown) {
// manage exceptions // if (response.errorThrown.name === 'SyntaxError') {
if (response.errorThrown) { // return 'Problem during data decoding [JSON]';
if (response.errorThrown.name === 'SyntaxError') { // }
return 'Problem during data decoding [JSON]'; // if (response.errorThrown.name === 'TimeoutError') {
} // return 'Server is taking too long to reply';
if (response.errorThrown.name === 'TimeoutError') { // }
return 'Server is taking too long to reply'; // if (response.errorThrown.name === 'AbortError') {
} // return 'Request cancelled on server';
if (response.errorThrown.name === 'AbortError') { // }
return 'Request cancelled on server'; // if (response.errorThrown.name === 'NetworkError') {
} // return 'A network error occurred';
if (response.errorThrown.name === 'NetworkError') { // }
return 'A network error occurred'; // throw response.errorThrown;
} // }
throw response.errorThrown;
} // // manage status
// if (response.status === 0) {
// return 'Server access problem. Check your network connection';
// }
// if (response.status === 401) {
// return 'Your session has expired, Please reconnect. [code: 401]';
// }
// if (response.status === 404) {
// return 'Page not found on server. [code: 404]';
// }
// if (response.status === 500) {
// return 'Internal server error. [code: 500]';
// }
// return `Unknown error. ${response.statusText?response.statusText:''}`;
// }
// manage status
if (response.status === 0) {
return 'Server access problem. Check your network connection';
}
if (response.status === 401) {
return 'Your session has expired, Please reconnect. [code: 401]';
}
if (response.status === 404) {
return 'Page not found on server. [code: 404]';
}
if (response.status === 500) {
return 'Internal server error. [code: 500]';
}
return 'Unknown error. ' + (response.statusText ? response.statusText : '');
}
}]); }]);
return Requester; return Requester;
}(); }();
@ -272,40 +295,30 @@ var Settings = function () {
'http GET transformer': { 'http GET transformer': {
uri: function uri(_ref) { uri: function uri(_ref) {
var _uri = _ref.uri; var _uri = _ref.uri,
var headers = _ref.headers; headers = _ref.headers,
var data = _ref.data; data = _ref.data;
if (!data) { if (!data) {
return _uri; return _uri;
} }
var uriWithoutAnchor = _uri,
anchor = '';
var anchor = ''; var match = /^(.*)(#.*)$/.exec(_uri);
var uriWithoutAnchor = _uri; if (match) {
var hashIndex = _uri.indexOf('#'); var _$exec = /^(.*)(#.*)$/.exec(_uri);
if (hashIndex >= 1) {
uriWithoutAnchor = _uri.slice(0, hashIndex); var _$exec2 = slicedToArray(_$exec, 3);
anchor = _uri.slice(hashIndex, _uri.length);
uriWithoutAnchor = _$exec2[1];
anchor = _$exec2[2];
} }
uriWithoutAnchor = Object.keys(data).reduce(function (gUri, d, index) { uriWithoutAnchor = Object.keys(data).reduce(function (gUri, d, index) {
if (index === 0 && gUri.indexOf('?') === -1) { gUri += '' + (index === 0 && gUri.indexOf('?') === -1 ? '?' : '&') + d + '=' + data[d];
gUri += '?';
} else {
gUri += '&';
}
gUri += d + '=' + data[d];
return gUri; return gUri;
}, uriWithoutAnchor); }, uriWithoutAnchor);
return uriWithoutAnchor + anchor; return uriWithoutAnchor + anchor;
},
data: function data(_ref2) {
var uri = _ref2.uri;
var headers = _ref2.headers;
var _data = _ref2.data;
return undefined;
} }
} }
}; };
@ -329,7 +342,7 @@ var Settings = function () {
createClass(Settings, [{ createClass(Settings, [{
key: 'set', key: 'set',
value: function set(name, value) { value: function set$$1(name, value) {
var checkRules = this.rules[name]; var checkRules = this.rules[name];
if (checkRules) { if (checkRules) {
checkRules(value); checkRules(value);
@ -346,7 +359,7 @@ var Settings = function () {
}, { }, {
key: 'get', key: 'get',
value: function get(name) { value: function get$$1(name) {
return this.settings[name]; return this.settings[name];
} }
}]); }]);
@ -367,7 +380,7 @@ var Middleware = function () {
*/ */
function Middleware() { function Middleware() {
var name = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
classCallCheck(this, Middleware); classCallCheck(this, Middleware);
this.name = name; this.name = name;
@ -384,66 +397,61 @@ var Middleware = function () {
* @public * @public
*/ */
// entered(request) { }
/**
* Invoked by the app before a new ajax request is sent or before the DOM is unloaded.
* See Application#_callMiddlewareExited documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
// exited(request) { }
/**
* Invoked by the app after an ajax request has responded or on DOM ready
* (document.readyState === 'interactive').
* See Application#_callMiddlewareUpdated documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
// updated(request, response) { }
/**
* Invoked by the app when an ajax request has failed.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
// failed(request, response) { }
/**
* Allow the hand over to the next middleware object or function.
*
* Override this method and return `false` to break execution of
* middleware chain.
*
* @return {Boolean} `true` by default
*
* @public
*/
createClass(Middleware, [{ createClass(Middleware, [{
key: 'entered',
value: function entered(request) {}
/**
* Invoked by the app before a new ajax request is sent or before the DOM is unloaded.
* See Application#_callMiddlewareExited documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
}, {
key: 'exited',
value: function exited(request) {}
/**
* Invoked by the app after an ajax request has responded or on DOM ready
* (document.readyState === 'interactive').
* See Application#_callMiddlewareUpdated documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
}, {
key: 'updated',
value: function updated(request, response) {}
/**
* Invoked by the app when an ajax request has failed.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
}, {
key: 'failed',
value: function failed(request, response) {}
/**
* Allow the hand over to the next middleware object or function.
*
* Override this method and return `false` to break execution of
* middleware chain.
*
* @return {Boolean} `true` by default
*
* @public
*/
}, {
key: 'next', key: 'next',
value: function next() { value: function next() {
return true; return true;
@ -488,7 +496,7 @@ var Route = function () {
createClass(Route, [{ createClass(Route, [{
key: 'uri', key: 'uri',
get: function get() { get: function get$$1() {
if (!this.uriPart && !this.method) { if (!this.uriPart && !this.method) {
return undefined; return undefined;
} }
@ -709,7 +717,7 @@ var Router = function () {
} }
}, { }, {
key: 'baseUri', key: 'baseUri',
set: function set(uri) { set: function set$$1(uri) {
if (!uri) { if (!uri) {
return; return;
} }
@ -735,7 +743,7 @@ var Router = function () {
*/ */
, ,
get: function get() { get: function get$$1() {
return this._baseUri; return this._baseUri;
} }
}]); }]);
@ -868,20 +876,19 @@ var Application = function () {
createClass(Application, [{ createClass(Application, [{
key: 'set', key: 'set',
value: function set() { value: function set$$1() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key]; args[_key] = arguments[_key];
} }
// get behaviour // get behaviour
if (args.length === 1) { if (args.length === 1) {
var _name = [args]; return this.settings.get([args]);
return this.settings.get(_name);
} }
// set behaviour // set behaviour
var name = args[0]; var name = args[0],
var value = args[1]; value = args[1];
this.settings.set(name, value); this.settings.set(name, value);
@ -910,19 +917,19 @@ var Application = function () {
var _this = this; var _this = this;
window.onbeforeunload = function () { window.onbeforeunload = function () {
_this._callMiddlewareExited(); _this._callMiddlewareMethod('exited');
}; };
window.onpopstate = function (event) { window.onpopstate = function (event) {
if (event.state) { if (event.state) {
var _event$state = event.state; var _event$state = event.state,
var request = _event$state.request; request = _event$state.request,
var response = _event$state.response; response = _event$state.response;
var currentRoutes = _this._routes(request.uri, request.method); var currentRoutes = _this._routes(request.uri, request.method);
_this._callMiddlewareEntered(currentRoutes, request); _this._callMiddlewareMethod('entered', currentRoutes, request);
_this._callMiddlewareUpdated(currentRoutes, request, response); _this._callMiddlewareMethod('updated', currentRoutes, request, response);
} }
}; };
@ -933,14 +940,14 @@ var Application = function () {
// DOM state // DOM state
if (document.readyState === 'loading' && !_this.isDOMLoaded) { if (document.readyState === 'loading' && !_this.isDOMLoaded) {
_this.isDOMLoaded = true; _this.isDOMLoaded = true;
_this._callMiddlewareEntered(currentRoutes, request); _this._callMiddlewareMethod('entered', currentRoutes, request);
} else if (document.readyState === 'interactive' && !_this.isDOMReady) { } else if (document.readyState === 'interactive' && !_this.isDOMReady) {
if (!_this.isDOMLoaded) { if (!_this.isDOMLoaded) {
_this.isDOMLoaded = true; _this.isDOMLoaded = true;
_this._callMiddlewareEntered(currentRoutes, request); _this._callMiddlewareMethod('entered', currentRoutes, request);
} }
_this.isDOMReady = true; _this.isDOMReady = true;
_this._callMiddlewareUpdated(currentRoutes, request, response); _this._callMiddlewareMethod('updated', currentRoutes, request, response);
if (callback) { if (callback) {
callback(request, response); callback(request, response);
} }
@ -993,30 +1000,24 @@ var Application = function () {
args[_key2] = arguments[_key2]; args[_key2] = arguments[_key2];
} }
if (args.length === 0) { var errorMsg = 'use method takes at least a middleware or a router';
throw new TypeError('use method takes at least a middleware or a router');
}
var baseUri = void 0, var baseUri = void 0,
middleware = void 0, middleware = void 0,
router = void 0, router = void 0,
which = void 0; which = void 0;
if (!args || args.length === 0) {
if (args.length === 1) { throw new TypeError(errorMsg);
} else if (args.length === 1) {
which = args[0]; which = args[0];
} else { } else {
baseUri = args[0]; baseUri = args[0];
which = args[1]; which = args[1];
} }
if (!(which instanceof Middleware) && typeof which !== 'function' && !(which instanceof Router)) {
throw new TypeError('use method takes at least a middleware or a router');
}
if (which instanceof Router) { if (which instanceof Router) {
router = which; router = which;
router.baseUri = baseUri; router.baseUri = baseUri;
} else { } else if (which instanceof Middleware || typeof which === 'function') {
middleware = which; middleware = which;
router = new Router(baseUri); router = new Router(baseUri);
var _iteratorNormalCompletion = true; var _iteratorNormalCompletion = true;
@ -1043,6 +1044,8 @@ var Application = function () {
} }
} }
} }
} else {
throw new TypeError(errorMsg);
} }
this.routers.push(router); this.routers.push(router);
@ -1059,8 +1062,8 @@ var Application = function () {
}, { }, {
key: '_routes', key: '_routes',
value: function _routes() { value: function _routes() {
var uri = arguments.length <= 0 || arguments[0] === undefined ? window.location.pathname + window.location.search : arguments[0]; var uri = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.pathname + window.location.search;
var method = arguments.length <= 1 || arguments[1] === undefined ? 'GET' : arguments[1]; var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GET';
var currentRoutes = []; var currentRoutes = [];
var _iteratorNormalCompletion2 = true; var _iteratorNormalCompletion2 = true;
@ -1071,8 +1074,7 @@ var Application = function () {
for (var _iterator2 = this.routers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { for (var _iterator2 = this.routers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var router = _step2.value; var router = _step2.value;
var routes = router.routes(uri, method); currentRoutes.push.apply(currentRoutes, toConsumableArray(router.routes(uri, method)));
currentRoutes.push.apply(currentRoutes, toConsumableArray(routes));
} }
} catch (err) { } catch (err) {
_didIteratorError2 = true; _didIteratorError2 = true;
@ -1093,146 +1095,95 @@ var Application = function () {
} }
/** /**
* Call `Middleware#entered` on _currentRoutes_. * Call `Middleware` method or middleware function on _currentRoutes_.
* Invoked before sending ajax request or when DOM
* is loading (document.readyState === 'loading').
* *
* @private * @private
*/ */
}, { }, {
key: '_callMiddlewareEntered', key: '_callMiddlewareMethod',
value: function _callMiddlewareEntered(currentRoutes, request) { value: function _callMiddlewareMethod(meth, currentRoutes, request, response) {
var _iteratorNormalCompletion3 = true; if (meth === 'exited') {
var _didIteratorError3 = false; // currentRoutes, request, response params not needed
var _iteratorError3 = undefined; var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = currentRoutes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var route = _step3.value;
if (route.middleware.entered) {
route.middleware.entered(request);
}
if (route.middleware.next && !route.middleware.next()) {
break;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try { try {
if (!_iteratorNormalCompletion3 && _iterator3.return) { for (var _iterator3 = this.routers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
_iterator3.return(); var router = _step3.value;
} var _iteratorNormalCompletion4 = true;
} finally { var _didIteratorError4 = false;
if (_didIteratorError3) { var _iteratorError4 = undefined;
throw _iteratorError3;
}
}
}
}
/** try {
* Call `Middleware#updated` or middleware function on _currentRoutes_. for (var _iterator4 = router.visited()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
* Invoked on ajax request responding or on DOM ready var route = _step4.value;
* (document.readyState === 'interactive').
*
* @private
*/
}, { if (route.middleware.exited) {
key: '_callMiddlewareUpdated', route.middleware.exited(route.visited);
value: function _callMiddlewareUpdated(currentRoutes, request, response) { route.visited = null;
var _iteratorNormalCompletion4 = true; }
var _didIteratorError4 = false; }
var _iteratorError4 = undefined; } catch (err) {
_didIteratorError4 = true;
try { _iteratorError4 = err;
for (var _iterator4 = currentRoutes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { } finally {
var route = _step4.value; try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
route.visited = request; _iterator4.return();
// calls middleware updated method }
if (route.middleware.updated) { } finally {
route.middleware.updated(request, response); if (_didIteratorError4) {
if (route.middleware.next && !route.middleware.next()) { throw _iteratorError4;
break; }
}
} }
} else { }
// calls middleware method } catch (err) {
var breakMiddlewareLoop = true; _didIteratorError3 = true;
var next = function next() { _iteratorError3 = err;
breakMiddlewareLoop = false; } finally {
}; try {
route.middleware(request, response, next); if (!_iteratorNormalCompletion3 && _iterator3.return) {
if (breakMiddlewareLoop) { _iterator3.return();
break; }
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
} }
} }
} }
} catch (err) {
_didIteratorError4 = true; return;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
} }
}
/**
* Call `Middleware#exited` on _currentRoutes_.
* Invoked before sending a new ajax request or before DOM unloading.
*
* @private
*/
}, {
key: '_callMiddlewareExited',
value: function _callMiddlewareExited() {
// calls middleware exited method
var _iteratorNormalCompletion5 = true; var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false; var _didIteratorError5 = false;
var _iteratorError5 = undefined; var _iteratorError5 = undefined;
try { try {
for (var _iterator5 = this.routers[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { for (var _iterator5 = currentRoutes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var router = _step5.value; var _route = _step5.value;
var routes = router.visited(); if (meth === 'updated') {
var _iteratorNormalCompletion6 = true; _route.visited = request;
var _didIteratorError6 = false; }
var _iteratorError6 = undefined;
try { if (_route.middleware[meth]) {
for (var _iterator6 = routes[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { _route.middleware[meth](request, response);
var route = _step6.value; if (_route.middleware.next && !_route.middleware.next()) {
break;
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
} }
} catch (err) { } else if (meth !== 'entered') {
_didIteratorError6 = true; // calls middleware method
_iteratorError6 = err; var breakMiddlewareLoop = true;
} finally { var next = function next() {
try { breakMiddlewareLoop = false;
if (!_iteratorNormalCompletion6 && _iterator6.return) { };
_iterator6.return(); _route.middleware(request, response, next);
} if (breakMiddlewareLoop) {
} finally { break;
if (_didIteratorError6) {
throw _iteratorError6;
}
} }
} }
} }
@ -1252,58 +1203,6 @@ var Application = function () {
} }
} }
/**
* Call `Middleware#failed` or middleware function on _currentRoutes_.
* Invoked when ajax request fails.
*
* @private
*/
}, {
key: '_callMiddlewareFailed',
value: function _callMiddlewareFailed(currentRoutes, request, response) {
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = currentRoutes[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var route = _step7.value;
// calls middleware failed method
if (route.middleware.failed) {
route.middleware.failed(request, response);
if (route.middleware.next && !route.middleware.next()) {
break;
}
} else {
// calls middleware method
var breakMiddlewareLoop = true;
var next = function next() {
breakMiddlewareLoop = false;
};
route.middleware(request, response, next);
if (breakMiddlewareLoop) {
break;
}
}
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
}
/** /**
* Make an ajax request. Manage History#pushState if history object set. * Make an ajax request. Manage History#pushState if history object set.
* *
@ -1315,11 +1214,11 @@ var Application = function () {
value: function _fetch(request, resolve, reject) { value: function _fetch(request, resolve, reject) {
var _this2 = this; var _this2 = this;
var method = request.method; var method = request.method,
var uri = request.uri; uri = request.uri,
var headers = request.headers; headers = request.headers,
var data = request.data; data = request.data,
var history = request.history; history = request.history;
var httpMethodTransformer = this.get('http ' + method + ' transformer'); var httpMethodTransformer = this.get('http ' + method + ' transformer');
@ -1330,25 +1229,25 @@ var Application = function () {
} }
// calls middleware exited method // calls middleware exited method
this._callMiddlewareExited(); this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri // gathers all routes impacted by the uri
var currentRoutes = this._routes(uri, method); var currentRoutes = this._routes(uri, method);
// calls middleware entered method // calls middleware entered method
this._callMiddlewareEntered(currentRoutes, request); this._callMiddlewareMethod('entered', currentRoutes, request);
// invokes http request // invokes http request
this.settings.get('http requester').fetch(request, function (req, res) { this.settings.get('http requester').fetch(request, function (req, res) {
if (history) { if (history) {
window.history.pushState({ request: req, response: res }, history.title, history.uri); window.history.pushState({ request: req, response: res }, history.title, history.uri);
} }
_this2._callMiddlewareUpdated(currentRoutes, req, res); _this2._callMiddlewareMethod('updated', currentRoutes, req, res);
if (resolve) { if (resolve) {
resolve(req, res); resolve(req, res);
} }
}, function (req, res) { }, function (req, res) {
_this2._callMiddlewareFailed(currentRoutes, req, res); _this2._callMiddlewareMethod('failed', currentRoutes, req, res);
if (reject) { if (reject) {
reject(req, res); reject(req, res);
} }
@ -1388,26 +1287,17 @@ HTTP_METHODS.reduce(function (reqProto, method) {
args[_key3] = arguments[_key3]; args[_key3] = arguments[_key3];
} }
if (middlewareMethodName === 'get') {
if (args.length === 0) {
throw new TypeError(middlewareMethodName + ' method takes at least a string or a middleware');
} else if (args.length === 1) {
var name = args[0];
if (typeof name === 'string') {
return this.settings.get(name);
}
}
} else if (args.length === 0) {
throw new TypeError(middlewareMethodName + ' method takes at least a middleware');
}
var baseUri = void 0, var baseUri = void 0,
middleware = void 0, middleware = void 0,
which = void 0; which = void 0;
if (!args || args.length === 0) {
if (args.length === 1) { throw new TypeError(middlewareMethodName + ' method takes at least a middleware ' + (middlewareMethodName === 'get' ? 'or a string' : ''));
} else if (args.length === 1) {
which = args[0]; which = args[0];
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
} else { } else {
baseUri = args[0]; baseUri = args[0];
which = args[1]; which = args[1];
@ -1417,8 +1307,8 @@ HTTP_METHODS.reduce(function (reqProto, method) {
throw new TypeError(middlewareMethodName + ' method takes at least a middleware'); throw new TypeError(middlewareMethodName + ' method takes at least a middleware');
} }
var router = new Router();
middleware = which; middleware = which;
var router = new Router();
router[middlewareMethodName](baseUri, middleware); router[middlewareMethodName](baseUri, middleware);
this.routers.push(router); this.routers.push(router);
@ -1448,10 +1338,10 @@ HTTP_METHODS.reduce(function (reqProto, method) {
*/ */
var httpMethodName = 'http' + method.charAt(0).toUpperCase() + method.slice(1).toLowerCase(); var httpMethodName = 'http' + method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
reqProto[httpMethodName] = function (request, resolve, reject) { reqProto[httpMethodName] = function (request, resolve, reject) {
var uri = request.uri; var uri = request.uri,
var headers = request.headers; headers = request.headers,
var data = request.data; data = request.data,
var history = request.history; history = request.history;
if (!uri) { if (!uri) {
uri = request; uri = request;
@ -1489,10 +1379,8 @@ var frontexpress = function frontexpress() {
frontexpress.Router = function (baseUri) { frontexpress.Router = function (baseUri) {
return new Router(baseUri); return new Router(baseUri);
}; };
frontexpress.Middleware = function (name) { frontexpress.Middleware = Middleware;
return new Middleware(name);
};
return frontexpress; return frontexpress;
}))); }());

2
frontexpress.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -48,8 +48,7 @@ export default class Application {
set(...args) { set(...args) {
// get behaviour // get behaviour
if (args.length === 1) { if (args.length === 1) {
const name = [args]; return this.settings.get([args]);
return this.settings.get(name);
} }
// set behaviour // set behaviour
@ -78,7 +77,7 @@ export default class Application {
listen(callback) { listen(callback) {
window.onbeforeunload = () => { window.onbeforeunload = () => {
this._callMiddlewareExited(); this._callMiddlewareMethod('exited');
}; };
window.onpopstate = (event) => { window.onpopstate = (event) => {
@ -86,8 +85,8 @@ export default class Application {
const {request, response} = event.state; const {request, response} = event.state;
const currentRoutes = this._routes(request.uri, request.method); const currentRoutes = this._routes(request.uri, request.method);
this._callMiddlewareEntered(currentRoutes, request); this._callMiddlewareMethod('entered', currentRoutes, request);
this._callMiddlewareUpdated(currentRoutes, request, response); this._callMiddlewareMethod('updated', currentRoutes, request, response);
} }
}; };
@ -98,14 +97,14 @@ export default class Application {
// DOM state // DOM state
if (document.readyState === 'loading' && !this.isDOMLoaded) { if (document.readyState === 'loading' && !this.isDOMLoaded) {
this.isDOMLoaded = true; this.isDOMLoaded = true;
this._callMiddlewareEntered(currentRoutes, request); this._callMiddlewareMethod('entered', currentRoutes, request);
} else if (document.readyState === 'interactive' && !this.isDOMReady) { } else if (document.readyState === 'interactive' && !this.isDOMReady) {
if (!this.isDOMLoaded) { if (!this.isDOMLoaded) {
this.isDOMLoaded = true; this.isDOMLoaded = true;
this._callMiddlewareEntered(currentRoutes, request); this._callMiddlewareMethod('entered', currentRoutes, request);
} }
this.isDOMReady = true; this.isDOMReady = true;
this._callMiddlewareUpdated(currentRoutes, request, response); this._callMiddlewareMethod('updated', currentRoutes, request, response);
if (callback) { if (callback) {
callback(request, response); callback(request, response);
} }
@ -152,31 +151,27 @@ export default class Application {
*/ */
use(...args) { use(...args) {
if (args.length === 0) { const errorMsg = 'use method takes at least a middleware or a router';
throw new TypeError('use method takes at least a middleware or a router');
}
let baseUri, middleware, router, which; let baseUri, middleware, router, which;
if (!args || args.length === 0) {
if (args.length === 1) { throw new TypeError(errorMsg);
} else if (args.length === 1) {
[which,] = args; [which,] = args;
} else { } else {
[baseUri, which,] = args; [baseUri, which,] = args;
} }
if (!(which instanceof Middleware) && (typeof which !== 'function') && !(which instanceof Router)) {
throw new TypeError('use method takes at least a middleware or a router');
}
if (which instanceof Router) { if (which instanceof Router) {
router = which; router = which;
router.baseUri = baseUri; router.baseUri = baseUri;
} else { } else if ((which instanceof Middleware) || (typeof which === 'function')) {
middleware = which; middleware = which;
router = new Router(baseUri); router = new Router(baseUri);
for (const method of HTTP_METHODS) { for (const method of HTTP_METHODS) {
router[method.toLowerCase()](middleware); router[method.toLowerCase()](middleware);
} }
} else {
throw new TypeError(errorMsg);
} }
this.routers.push(router); this.routers.push(router);
@ -194,8 +189,7 @@ export default class Application {
_routes(uri=window.location.pathname + window.location.search, method='GET') { _routes(uri=window.location.pathname + window.location.search, method='GET') {
const currentRoutes = []; const currentRoutes = [];
for (const router of this.routers) { for (const router of this.routers) {
const routes = router.routes(uri, method); currentRoutes.push(...router.routes(uri, method));
currentRoutes.push(...routes);
} }
return currentRoutes; return currentRoutes;
@ -203,95 +197,37 @@ export default class Application {
/** /**
* Call `Middleware#entered` on _currentRoutes_. * Call `Middleware` method or middleware function on _currentRoutes_.
* Invoked before sending ajax request or when DOM
* is loading (document.readyState === 'loading').
* *
* @private * @private
*/ */
_callMiddlewareEntered(currentRoutes, request) { _callMiddlewareMethod(meth, currentRoutes, request, response) {
for (const route of currentRoutes) { if (meth === 'exited') {
if (route.middleware.entered) { // currentRoutes, request, response params not needed
route.middleware.entered(request); for (const router of this.routers) {
} for (const route of router.visited()) {
if (route.middleware.next && !route.middleware.next()) { if (route.middleware.exited) {
break; route.middleware.exited(route.visited);
route.visited = null;
}
}
} }
return;
} }
}
/**
* Call `Middleware#updated` or middleware function on _currentRoutes_.
* Invoked on ajax request responding or on DOM ready
* (document.readyState === 'interactive').
*
* @private
*/
_callMiddlewareUpdated(currentRoutes, request, response) {
for (const route of currentRoutes) { for (const route of currentRoutes) {
route.visited = request; if (meth === 'updated') {
// calls middleware updated method route.visited = request;
if (route.middleware.updated) { }
route.middleware.updated(request, response);
if (route.middleware[meth]) {
route.middleware[meth](request, response);
if (route.middleware.next && !route.middleware.next()) { if (route.middleware.next && !route.middleware.next()) {
break; break;
} }
} else { } else if (meth !== 'entered') {
// calls middleware method // calls middleware method
let breakMiddlewareLoop = true;
const next = () => {
breakMiddlewareLoop = false;
};
route.middleware(request, response, next);
if (breakMiddlewareLoop) {
break;
}
}
}
}
/**
* Call `Middleware#exited` on _currentRoutes_.
* Invoked before sending a new ajax request or before DOM unloading.
*
* @private
*/
_callMiddlewareExited() {
// calls middleware exited method
for (const router of this.routers) {
const routes = router.visited();
for (const route of routes) {
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
}
}
}
/**
* Call `Middleware#failed` or middleware function on _currentRoutes_.
* Invoked when ajax request fails.
*
* @private
*/
_callMiddlewareFailed(currentRoutes, request, response) {
for (const route of currentRoutes) {
// calls middleware failed method
if (route.middleware.failed) {
route.middleware.failed(request, response);
if (route.middleware.next && !route.middleware.next()) {
break;
}
} else {
// calls middleware method
let breakMiddlewareLoop = true; let breakMiddlewareLoop = true;
const next = () => { const next = () => {
breakMiddlewareLoop = false; breakMiddlewareLoop = false;
@ -322,13 +258,13 @@ export default class Application {
} }
// calls middleware exited method // calls middleware exited method
this._callMiddlewareExited(); this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri // gathers all routes impacted by the uri
const currentRoutes = this._routes(uri, method); const currentRoutes = this._routes(uri, method);
// calls middleware entered method // calls middleware entered method
this._callMiddlewareEntered(currentRoutes, request); this._callMiddlewareMethod('entered', currentRoutes, request);
// invokes http request // invokes http request
this.settings.get('http requester').fetch(request, this.settings.get('http requester').fetch(request,
@ -336,13 +272,13 @@ export default class Application {
if (history) { if (history) {
window.history.pushState({request: req, response: res}, history.title, history.uri); window.history.pushState({request: req, response: res}, history.title, history.uri);
} }
this._callMiddlewareUpdated(currentRoutes, req, res); this._callMiddlewareMethod('updated', currentRoutes, req, res);
if (resolve) { if (resolve) {
resolve(req, res); resolve(req, res);
} }
}, },
(req, res) => { (req, res) => {
this._callMiddlewareFailed(currentRoutes, req, res); this._callMiddlewareMethod('failed', currentRoutes, req, res);
if (reject) { if (reject) {
reject(req, res); reject(req, res);
} }
@ -377,23 +313,14 @@ HTTP_METHODS.reduce((reqProto, method) => {
const middlewareMethodName = method.toLowerCase(); const middlewareMethodName = method.toLowerCase();
reqProto[middlewareMethodName] = function(...args) { reqProto[middlewareMethodName] = function(...args) {
if (middlewareMethodName === 'get') {
if (args.length === 0) {
throw new TypeError(`${middlewareMethodName} method takes at least a string or a middleware`);
} else if (args.length === 1) {
const [name] = args;
if (typeof name === 'string') {
return this.settings.get(name);
}
}
} else if (args.length === 0) {
throw new TypeError(`${middlewareMethodName} method takes at least a middleware`);
}
let baseUri, middleware, which; let baseUri, middleware, which;
if (!args || args.length === 0) {
if (args.length === 1) { throw new TypeError(`${middlewareMethodName} method takes at least a middleware ${middlewareMethodName === 'get' ? 'or a string' : ''}`);
[which,] = args; } else if (args.length === 1) {
[which] = args;
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
} else { } else {
[baseUri, which,] = args; [baseUri, which,] = args;
} }
@ -402,8 +329,8 @@ HTTP_METHODS.reduce((reqProto, method) => {
throw new TypeError(`${middlewareMethodName} method takes at least a middleware`); throw new TypeError(`${middlewareMethodName} method takes at least a middleware`);
} }
const router = new Router();
middleware = which; middleware = which;
const router = new Router();
router[middlewareMethodName](baseUri, middleware); router[middlewareMethodName](baseUri, middleware);
this.routers.push(router); this.routers.push(router);
@ -447,4 +374,4 @@ HTTP_METHODS.reduce((reqProto, method) => {
}; };
return reqProto; return reqProto;
}, Application.prototype); }, Application.prototype);

View File

@ -20,6 +20,6 @@ const frontexpress = () => new Application();
* Expose Router, Middleware constructors. * Expose Router, Middleware constructors.
*/ */
frontexpress.Router = (baseUri) => new Router(baseUri); frontexpress.Router = (baseUri) => new Router(baseUri);
frontexpress.Middleware = (name) => new Middleware(name); frontexpress.Middleware = Middleware;
export default frontexpress; export default frontexpress;

View File

@ -3,4 +3,6 @@
* @private * @private
*/ */
export default ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH']; export default ['GET', 'POST', 'PUT', 'DELETE'];
// not supported yet
// HEAD', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH';

View File

@ -27,7 +27,7 @@ export default class Middleware {
* @public * @public
*/ */
entered(request) { } // entered(request) { }
/** /**
@ -40,7 +40,7 @@ export default class Middleware {
* @public * @public
*/ */
exited(request) { } // exited(request) { }
/** /**
@ -55,7 +55,7 @@ export default class Middleware {
* @public * @public
*/ */
updated(request, response) { } // updated(request, response) { }
/** /**
@ -67,7 +67,7 @@ export default class Middleware {
* @param {Object} response * @param {Object} response
* @public * @public
*/ */
failed(request, response) { } // failed(request, response) { }
/** /**

View File

@ -20,15 +20,25 @@ export default class Requester {
const success = (responseText) => { const success = (responseText) => {
resolve( resolve(
request, request,
{status: 200, statusText: 'OK', responseText} {
status: 200,
statusText: 'OK',
responseText
}
); );
}; };
const fail = ({status, statusText, errorThrown}) => { const fail = ({status, statusText, errorThrown}) => {
const errors = this._analyzeErrors({status, statusText, errorThrown}); // Removed for reducing size of frontexpress
// const errors = this._analyzeErrors({status, statusText, errorThrown});
reject( reject(
request, request,
{status, statusText, errorThrown, errors} {
status,
statusText,
errorThrown,
errors: `HTTP ${status} ${statusText?statusText:''}`
}
); );
}; };
@ -59,44 +69,44 @@ export default class Requester {
} }
} }
// Removed for reducing size of frontexpress
// /**
// * Analyse response errors.
// *
// * @private
// */
/** // _analyzeErrors(response) {
* Analyse response errors. // // manage exceptions
* // if (response.errorThrown) {
* @private // if (response.errorThrown.name === 'SyntaxError') {
*/ // return 'Problem during data decoding [JSON]';
// }
// if (response.errorThrown.name === 'TimeoutError') {
// return 'Server is taking too long to reply';
// }
// if (response.errorThrown.name === 'AbortError') {
// return 'Request cancelled on server';
// }
// if (response.errorThrown.name === 'NetworkError') {
// return 'A network error occurred';
// }
// throw response.errorThrown;
// }
_analyzeErrors(response) { // // manage status
// manage exceptions // if (response.status === 0) {
if (response.errorThrown) { // return 'Server access problem. Check your network connection';
if (response.errorThrown.name === 'SyntaxError') { // }
return 'Problem during data decoding [JSON]'; // if (response.status === 401) {
} // return 'Your session has expired, Please reconnect. [code: 401]';
if (response.errorThrown.name === 'TimeoutError') { // }
return 'Server is taking too long to reply'; // if (response.status === 404) {
} // return 'Page not found on server. [code: 404]';
if (response.errorThrown.name === 'AbortError') { // }
return 'Request cancelled on server'; // if (response.status === 500) {
} // return 'Internal server error. [code: 500]';
if (response.errorThrown.name === 'NetworkError') { // }
return 'A network error occurred'; // return `Unknown error. ${response.statusText?response.statusText:''}`;
} // }
throw response.errorThrown; }
}
// manage status
if (response.status === 0) {
return 'Server access problem. Check your network connection';
}
if (response.status === 401) {
return 'Your session has expired, Please reconnect. [code: 401]';
}
if (response.status === 404) {
return 'Page not found on server. [code: 404]';
}
if (response.status === 500) {
return 'Internal server error. [code: 500]';
}
return `Unknown error. ${response.statusText?response.statusText:''}`;
}
}

View File

@ -32,29 +32,16 @@ export default class Settings {
if (!data) { if (!data) {
return uri; return uri;
} }
let [uriWithoutAnchor, anchor] = [uri, ''];
let anchor = ''; const match = /^(.*)(#.*)$/.exec(uri);
let uriWithoutAnchor = uri; if (match) {
const hashIndex = uri.indexOf('#'); [,uriWithoutAnchor, anchor] = /^(.*)(#.*)$/.exec(uri);
if (hashIndex >=1) {
uriWithoutAnchor = uri.slice(0, hashIndex);
anchor = uri.slice(hashIndex, uri.length);
} }
uriWithoutAnchor = Object.keys(data).reduce((gUri, d, index) => { uriWithoutAnchor = Object.keys(data).reduce((gUri, d, index) => {
if (index === 0 && gUri.indexOf('?') === -1) { gUri += `${(index === 0 && gUri.indexOf('?') === -1)?'?':'&'}${d}=${data[d]}`;
gUri += '?';
} else {
gUri += '&';
}
gUri += `${d}=${data[d]}`;
return gUri; return gUri;
}, uriWithoutAnchor); }, uriWithoutAnchor);
return uriWithoutAnchor + anchor; return uriWithoutAnchor + anchor;
},
data({uri, headers, data}) {
return undefined;
} }
} }
}; };
@ -96,4 +83,4 @@ export default class Settings {
get(name) { get(name) {
return this.settings[name]; return this.settings[name];
} }
}; };

View File

@ -1,6 +1,6 @@
{ {
"name": "frontexpress", "name": "frontexpress",
"version": "0.1.10", "version": "1.0.0",
"description": "Frontexpress manages routes in browser like ExpressJS on Node", "description": "Frontexpress manages routes in browser like ExpressJS on Node",
"main": "dist/frontexpress.js", "main": "dist/frontexpress.js",
"scripts": { "scripts": {
@ -28,25 +28,26 @@
"frontexpress" "frontexpress"
], ],
"devDependencies": { "devDependencies": {
"babel-cli": "^6.10.1", "babel-cli": "^6.18.0",
"babel-core": "^6.14.0", "babel-core": "^6.21.0",
"babel-eslint": "^6.1.2", "babel-eslint": "^7.1.1",
"babel-istanbul": "^0.11.0", "babel-istanbul": "^0.12.1",
"babel-plugin-add-module-exports": "^0.2.1", "babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-es2015": "^6.14.0", "babel-preset-babili": "0.0.9",
"babel-preset-es2015-rollup": "^1.2.0", "babel-preset-es2015": "^6.18.0",
"babel-register": "^6.14.0", "babel-preset-es2015-rollup": "^3.0.0",
"babel-register": "^6.18.0",
"chai": "^3.5.0", "chai": "^3.5.0",
"eslint": "^3.1.0", "eslint": "^3.12.2",
"eslint-loader": "^1.4.1", "eslint-loader": "^1.6.1",
"expose-loader": "^0.7.1", "expose-loader": "^0.7.1",
"istanbul": "^0.4.4", "istanbul": "^0.4.5",
"mocha": "^2.5.3", "mocha": "^3.2.0",
"rimraf": "^2.5.3", "rimraf": "^2.5.4",
"rollup": "^0.35.10", "rollup": "^0.38.3",
"rollup-plugin-babel": "^2.6.1", "rollup-plugin-babel": "^2.7.1",
"rollup-plugin-uglify": "^1.0.1", "rollup-plugin-uglify": "^1.0.1",
"sinon": "^1.17.4", "sinon": "^1.17.6",
"uglify-js": "^2.7.3" "uglify-js": "github:mishoo/UglifyJS2#harmony"
} }
} }

View File

@ -1,13 +1,15 @@
import babel from 'rollup-plugin-babel'; import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
export default { export default {
entry: 'lib/frontexpress.js', entry: 'lib/frontexpress.js',
format: 'umd', format: 'iife',
moduleName:'frontexpress', moduleName:'frontexpress',
plugins: [babel({ plugins: [babel({
babelrc: false, babelrc: false,
presets: ['es2015-rollup'] // exclude: 'node_modules/**',
presets: ['es2015-rollup'],
// externalHelpers: true,
// plugins: ['external-helpers']
})], })],
dest: 'frontexpress.js' dest: 'frontexpress.js'
}; };

View File

@ -1,14 +1,28 @@
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify'; import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-js';
import babel from 'rollup-plugin-babel';
export default { export default {
entry: 'lib/frontexpress.js', entry: 'lib/frontexpress.js',
format: 'umd', format: 'iife',
sourceMap: true, sourceMap: true,
moduleName:'frontexpress', moduleName:'frontexpress',
plugins: [babel({ dest: 'frontexpress.min.js',
babelrc: false, plugins: [
presets: ['es2015-rollup'] babel({
}), uglify()], babelrc: false,
dest: 'frontexpress.min.js' // exclude: 'node_modules/**',
}; presets: ['es2015-rollup'],
// externalHelpers: true,
// plugins: ['external-helpers']
}),
uglify({
compress: {
warnings: false,
},
output: {
comments: false
}
}, minify)
]
};

View File

@ -6,6 +6,13 @@ import frontexpress from '../lib/frontexpress';
import Requester from '../lib/requester'; import Requester from '../lib/requester';
describe('Application', () => { describe('Application', () => {
class MyMiddleware extends frontexpress.Middleware {
entered() {}
exited() {}
failed() {}
updated() {}
}
let requester; let requester;
describe('generated methods', () => { describe('generated methods', () => {
@ -65,7 +72,7 @@ describe('Application', () => {
// const spy_pushState = sinon.spy(window.history, 'pushState'); // const spy_pushState = sinon.spy(window.history, 'pushState');
// const app = frontexpress(); // const app = frontexpress();
// const m = frontexpress.Middleware(); // const m = new MyMiddleware();
// const spy_middleware = sinon.stub(m, 'updated'); // const spy_middleware = sinon.stub(m, 'updated');
// app.set('http requester', requester); // app.set('http requester', requester);
@ -146,7 +153,7 @@ describe('Application', () => {
it('with middleware object readyState===loading', (done) => { it('with middleware object readyState===loading', (done) => {
const app = frontexpress(); const app = frontexpress();
const m = frontexpress.Middleware(); const m = new MyMiddleware();
sinon.stub(m, 'entered', () => { sinon.stub(m, 'entered', () => {
done(); done();
}); });
@ -161,7 +168,7 @@ describe('Application', () => {
it('with middleware object readyState===interactive', (done) => { it('with middleware object readyState===interactive', (done) => {
const app = frontexpress(); const app = frontexpress();
const m = frontexpress.Middleware(); const m = new MyMiddleware();
sinon.stub(m, 'updated', () => { sinon.stub(m, 'updated', () => {
done(); done();
}); });
@ -176,7 +183,7 @@ describe('Application', () => {
it('with middleware object event beforeunload', (done) => { it('with middleware object event beforeunload', (done) => {
const app = frontexpress(); const app = frontexpress();
const m = frontexpress.Middleware(); const m = new MyMiddleware();
sinon.stub(m, 'exited', () => { sinon.stub(m, 'exited', () => {
done(); done();
}); });
@ -205,7 +212,7 @@ describe('Application', () => {
const spy_pushState = sinon.spy(window.history, 'pushState'); const spy_pushState = sinon.spy(window.history, 'pushState');
const app = frontexpress(); const app = frontexpress();
const m = frontexpress.Middleware(); const m = new MyMiddleware();
const spy_middleware = sinon.stub(m, 'updated', (req, res) => { const spy_middleware = sinon.stub(m, 'updated', (req, res) => {
historyObj = req.history; historyObj = req.history;
}); });
@ -252,7 +259,7 @@ describe('Application', () => {
const spy_pushState = sinon.spy(window.history, 'pushState'); const spy_pushState = sinon.spy(window.history, 'pushState');
const app = frontexpress(); const app = frontexpress();
const m = frontexpress.Middleware(); const m = new MyMiddleware();
const spy_middleware = sinon.stub(m, 'updated', (req, res) => { const spy_middleware = sinon.stub(m, 'updated', (req, res) => {
historyObj = req.history; historyObj = req.history;
}); });
@ -404,7 +411,7 @@ describe('Application', () => {
}); });
it('middleware as object on path /', (done) => { it('middleware as object on path /', (done) => {
const middleware = frontexpress.Middleware('on path /'); const middleware = new MyMiddleware('on path /');
const spy = sinon.spy(middleware, 'updated'); const spy = sinon.spy(middleware, 'updated');
const app = frontexpress(); const app = frontexpress();
@ -422,7 +429,7 @@ describe('Application', () => {
}); });
it('middleware as object on path /route1', (done) => { it('middleware as object on path /route1', (done) => {
const middleware = frontexpress.Middleware('on path /route1'); const middleware = new MyMiddleware('on path /route1');
const spy = sinon.spy(middleware, 'updated'); const spy = sinon.spy(middleware, 'updated');
const app = frontexpress(); const app = frontexpress();
@ -448,7 +455,7 @@ describe('Application', () => {
); );
}); });
const middleware = frontexpress.Middleware('on path /'); const middleware = new MyMiddleware('on path /');
const spy = sinon.spy(middleware, 'failed'); const spy = sinon.spy(middleware, 'failed');
const app = frontexpress(); const app = frontexpress();
@ -505,7 +512,7 @@ describe('Application', () => {
}); });
it('router with base uri', (done)=> { it('router with base uri', (done)=> {
const middleware = frontexpress.Middleware('get middleware'); const middleware = new MyMiddleware('get middleware');
const spy = sinon.spy(middleware, 'updated'); const spy = sinon.spy(middleware, 'updated');
const app = frontexpress(); const app = frontexpress();
@ -528,12 +535,12 @@ describe('Application', () => {
it('use two routers', (done)=> { it('use two routers', (done)=> {
const router1 = frontexpress.Router(); const router1 = frontexpress.Router();
const m1 = frontexpress.Middleware(); const m1 = new MyMiddleware();
const spy1 = sinon.spy(m1, 'updated'); const spy1 = sinon.spy(m1, 'updated');
router1.get('/subroute1', m1); router1.get('/subroute1', m1);
const router2 = frontexpress.Router(); const router2 = frontexpress.Router();
const m2 = frontexpress.Middleware(); const m2 = new MyMiddleware();
const spy2 = sinon.spy(m2, 'updated'); const spy2 = sinon.spy(m2, 'updated');
router2.get('/subroute2', m2); router2.get('/subroute2', m2);
@ -621,7 +628,7 @@ describe('Application', () => {
}); });
it('middleware as object on path /', (done) => { it('middleware as object on path /', (done) => {
const middleware = frontexpress.Middleware('on path /'); const middleware = new MyMiddleware('on path /');
const spy = sinon.spy(middleware, 'updated'); const spy = sinon.spy(middleware, 'updated');
const app = frontexpress(); const app = frontexpress();
@ -639,7 +646,7 @@ describe('Application', () => {
}); });
it('middleware as object on path /route1', (done) => { it('middleware as object on path /route1', (done) => {
const middleware = frontexpress.Middleware('on path /route1'); const middleware = new MyMiddleware('on path /route1');
const spy = sinon.spy(middleware, 'updated'); const spy = sinon.spy(middleware, 'updated');
const app = frontexpress(); const app = frontexpress();
@ -801,7 +808,7 @@ describe('Application', () => {
const app = frontexpress(); const app = frontexpress();
app.set('http requester', requester); app.set('http requester', requester);
const getMiddleware = frontexpress.Middleware('get middleware'); const getMiddleware = new MyMiddleware('get middleware');
const spy_get_entered = sinon.spy(getMiddleware, 'entered'); const spy_get_entered = sinon.spy(getMiddleware, 'entered');
const spy_get_updated = sinon.spy(getMiddleware, 'updated'); const spy_get_updated = sinon.spy(getMiddleware, 'updated');
const spy_get_exited = sinon.spy(getMiddleware, 'exited'); const spy_get_exited = sinon.spy(getMiddleware, 'exited');
@ -829,17 +836,17 @@ describe('Application', () => {
const app = frontexpress(); const app = frontexpress();
app.set('http requester', requester); app.set('http requester', requester);
const allMiddleware = frontexpress.Middleware('all middleware'); const allMiddleware = new MyMiddleware('all middleware');
const spy_all_entered = sinon.spy(allMiddleware, 'entered'); const spy_all_entered = sinon.spy(allMiddleware, 'entered');
const spy_all_updated = sinon.spy(allMiddleware, 'updated'); const spy_all_updated = sinon.spy(allMiddleware, 'updated');
const spy_all_exited = sinon.spy(allMiddleware, 'exited'); const spy_all_exited = sinon.spy(allMiddleware, 'exited');
const getMiddleware = frontexpress.Middleware('get middleware'); const getMiddleware = new MyMiddleware('get middleware');
const spy_get_entered = sinon.spy(getMiddleware, 'entered'); const spy_get_entered = sinon.spy(getMiddleware, 'entered');
const spy_get_updated = sinon.spy(getMiddleware, 'updated'); const spy_get_updated = sinon.spy(getMiddleware, 'updated');
const spy_get_exited = sinon.spy(getMiddleware, 'exited'); const spy_get_exited = sinon.spy(getMiddleware, 'exited');
const postMiddleware = frontexpress.Middleware('post middleware'); const postMiddleware = new MyMiddleware('post middleware');
const spy_post_entered = sinon.spy(postMiddleware, 'entered'); const spy_post_entered = sinon.spy(postMiddleware, 'entered');
const spy_post_updated = sinon.spy(postMiddleware, 'updated'); const spy_post_updated = sinon.spy(postMiddleware, 'updated');
const spy_post_exited = sinon.spy(postMiddleware, 'exited'); const spy_post_exited = sinon.spy(postMiddleware, 'exited');
@ -912,7 +919,7 @@ describe('Application', () => {
const app = frontexpress(); const app = frontexpress();
app.set('http requester', requester); app.set('http requester', requester);
const getMiddleware = frontexpress.Middleware('get middleware'); const getMiddleware = new MyMiddleware('get middleware');
const spy_get_failed = sinon.spy(getMiddleware, 'failed'); const spy_get_failed = sinon.spy(getMiddleware, 'failed');
@ -931,10 +938,10 @@ describe('Application', () => {
const app = frontexpress(); const app = frontexpress();
app.set('http requester', requester); app.set('http requester', requester);
const m1 = frontexpress.Middleware('m1'); const m1 = new MyMiddleware('m1');
const m2 = frontexpress.Middleware('m2'); const m2 = new MyMiddleware('m2');
m2.next = () => false; m2.next = () => false;
const m3 = frontexpress.Middleware('m3'); const m3 = new MyMiddleware('m3');
const spy_m1 = sinon.spy(m1, 'updated'); const spy_m1 = sinon.spy(m1, 'updated');
const spy_m2 = sinon.spy(m2, 'updated'); const spy_m2 = sinon.spy(m2, 'updated');

View File

@ -18,10 +18,10 @@ describe('frontexpress', () => {
it('test Middleware class exposed', () => { it('test Middleware class exposed', () => {
assert(frontexpress.Middleware); assert(frontexpress.Middleware);
assert(frontexpress.Middleware() instanceof Middleware); assert(new frontexpress.Middleware() instanceof Middleware);
const m1 = frontexpress.Middleware(); const m1 = new frontexpress.Middleware();
const m2 = frontexpress.Middleware(); const m2 = new frontexpress.Middleware();
assert(m1 !== m2); assert(m1 !== m2);
}); });
@ -33,4 +33,4 @@ describe('frontexpress', () => {
const app2 = frontexpress(); const app2 = frontexpress();
assert(app1 !== app2); assert(app1 !== app2);
}); });
}); });

View File

@ -378,15 +378,16 @@ describe('Requester', () => {
}); });
}); });
it('request returns unknown error', () => { // Removed for reducing size of frontexpress
const requester = new Requester(); // it('request returns unknown error', () => {
// const requester = new Requester();
const {stub_open, stub_send} = xHttpWillThrow(xhttp, 'BlaBlaError'); // const {stub_open, stub_send} = xHttpWillThrow(xhttp, 'BlaBlaError');
chai.expect(() => { // chai.expect(() => {
requester.fetch({method: 'GET', uri:'/route1'}); // requester.fetch({method: 'GET', uri:'/route1'});
}).to.throw(/BlaBlaError/); // }).to.throw(/BlaBlaError/);
}); // });
}); });
}); });

View File

@ -103,7 +103,7 @@ describe('Router', () => {
it('no root path and regexp uri', ()=> { it('no root path and regexp uri', ()=> {
const router = frontexpress.Router(); const router = frontexpress.Router();
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
router.get(/^\/route1/, middleware); router.get(/^\/route1/, middleware);
@ -118,7 +118,7 @@ describe('Router', () => {
it('with root path /route1 and path /subroute', () => { it('with root path /route1 and path /subroute', () => {
const router = frontexpress.Router('/route1'); const router = frontexpress.Router('/route1');
router.get('/subroute', frontexpress.Middleware()); router.get('/subroute', new frontexpress.Middleware());
const r = router.routes('/route1/subroute', 'GET'); const r = router.routes('/route1/subroute', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -128,7 +128,7 @@ describe('Router', () => {
it('with root path /route1 and no path uri', () => { it('with root path /route1 and no path uri', () => {
const router = frontexpress.Router('/route1'); const router = frontexpress.Router('/route1');
router.get(frontexpress.Middleware()); router.get(new frontexpress.Middleware());
const r = router.routes('/route1', 'GET'); const r = router.routes('/route1', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -138,7 +138,7 @@ describe('Router', () => {
it('duplicate / in route', () => { it('duplicate / in route', () => {
const router = frontexpress.Router('/route1/'); const router = frontexpress.Router('/route1/');
router.get('/subroute', frontexpress.Middleware()); router.get('/subroute', new frontexpress.Middleware());
const r = router.routes('/route1/subroute', 'GET'); const r = router.routes('/route1/subroute', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -148,7 +148,7 @@ describe('Router', () => {
it('spaces in route', () => { it('spaces in route', () => {
let router = frontexpress.Router(' /route1 '); let router = frontexpress.Router(' /route1 ');
router.get('/subroute ', frontexpress.Middleware()); router.get('/subroute ', new frontexpress.Middleware());
let r = router.routes('/route1/subroute', 'GET'); let r = router.routes('/route1/subroute', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -158,7 +158,7 @@ describe('Router', () => {
router = frontexpress.Router(' /route1 '); router = frontexpress.Router(' /route1 ');
router.get(frontexpress.Middleware()); router.get(new frontexpress.Middleware());
r = router.routes('/route1', 'GET'); r = router.routes('/route1', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -168,7 +168,7 @@ describe('Router', () => {
it('route with query string', () => { it('route with query string', () => {
let router = frontexpress.Router('/route1 '); let router = frontexpress.Router('/route1 ');
router.get('/subroute', frontexpress.Middleware()); router.get('/subroute', new frontexpress.Middleware());
let r = router.routes('/route1/subroute?a=b&c=d', 'GET'); let r = router.routes('/route1/subroute?a=b&c=d', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -179,7 +179,7 @@ describe('Router', () => {
it('route with anchor', () => { it('route with anchor', () => {
let router = frontexpress.Router('/route1 '); let router = frontexpress.Router('/route1 ');
router.get('/subroute', frontexpress.Middleware()); router.get('/subroute', new frontexpress.Middleware());
let r = router.routes('/route1/subroute#a=b&c=d', 'GET'); let r = router.routes('/route1/subroute#a=b&c=d', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -190,7 +190,7 @@ describe('Router', () => {
it('route with query string and anchor', () => { it('route with query string and anchor', () => {
let router = frontexpress.Router('/route1 '); let router = frontexpress.Router('/route1 ');
router.get('/subroute', frontexpress.Middleware()); router.get('/subroute', new frontexpress.Middleware());
let r = router.routes('/route1/subroute?a=b&c=d#anchor1', 'GET'); let r = router.routes('/route1/subroute?a=b&c=d#anchor1', 'GET');
assert(r.length === 1); assert(r.length === 1);
@ -214,7 +214,7 @@ describe('Router', () => {
it('only middleware as argument', () => { it('only middleware as argument', () => {
const router = frontexpress.Router('/route1'); const router = frontexpress.Router('/route1');
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
const spied_methods = []; const spied_methods = [];
for (const method of HTTP_METHODS) { for (const method of HTTP_METHODS) {
@ -230,7 +230,7 @@ describe('Router', () => {
it('with path /route1 and middleware as arguments', () => { it('with path /route1 and middleware as arguments', () => {
const router = frontexpress.Router(); const router = frontexpress.Router();
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
const spied_methods = []; const spied_methods = [];
for (const method of HTTP_METHODS) { for (const method of HTTP_METHODS) {
@ -260,7 +260,7 @@ describe('Router', () => {
it('only middleware as argument', () => { it('only middleware as argument', () => {
const router = frontexpress.Router('/'); const router = frontexpress.Router('/');
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
router.get(middleware); router.get(middleware);
@ -273,7 +273,7 @@ describe('Router', () => {
it('with path /route1 and middleware as arguments', () => { it('with path /route1 and middleware as arguments', () => {
const router = frontexpress.Router(); const router = frontexpress.Router();
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
router.get('/route1', middleware); router.get('/route1', middleware);
@ -286,13 +286,13 @@ describe('Router', () => {
it('router with regexp and route with /route1', () => { it('router with regexp and route with /route1', () => {
const router = frontexpress.Router(/^\//); const router = frontexpress.Router(/^\//);
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
chai.expect(() => router.get('/route1', middleware)).to.throw(TypeError); chai.expect(() => router.get('/route1', middleware)).to.throw(TypeError);
}); });
it('router with regexp and route without uri', () => { it('router with regexp and route without uri', () => {
const router = frontexpress.Router(/^\/part/); const router = frontexpress.Router(/^\/part/);
const middleware = frontexpress.Middleware(); const middleware = new frontexpress.Middleware();
router.get(middleware); router.get(middleware);
const r = router.routes('/part1', 'GET'); const r = router.routes('/part1', 'GET');

View File

@ -11,7 +11,7 @@ describe('Settings', () => {
const dataFn = settings.get('http GET transformer').data; const dataFn = settings.get('http GET transformer').data;
assert(uriFn({uri: '/route', data:{a:'b', c:'d'}}) === '/route?a=b&c=d'); assert(uriFn({uri: '/route', data:{a:'b', c:'d'}}) === '/route?a=b&c=d');
assert(dataFn({uri: '/route', data:{a:'b', c:'d'}}) === undefined); assert(dataFn === undefined);
}); });
it('uri with query string', () => { it('uri with query string', () => {
@ -19,7 +19,7 @@ describe('Settings', () => {
const dataFn = settings.get('http GET transformer').data; const dataFn = settings.get('http GET transformer').data;
assert(uriFn({uri: '/route?x=y&z=a', data:{a:'b', c:'d'}}) === '/route?x=y&z=a&a=b&c=d'); assert(uriFn({uri: '/route?x=y&z=a', data:{a:'b', c:'d'}}) === '/route?x=y&z=a&a=b&c=d');
assert(dataFn({uri: '/route?x=y&z=a', data:{a:'b', c:'d'}}) === undefined); assert(dataFn === undefined);
}); });
it('uri with query string and anchor', () => { it('uri with query string and anchor', () => {
@ -27,7 +27,7 @@ describe('Settings', () => {
const dataFn = settings.get('http GET transformer').data; const dataFn = settings.get('http GET transformer').data;
assert(uriFn({uri: '/route?x=y&z=a#anchor1', data:{a:'b', c:'d'}}) === '/route?x=y&z=a&a=b&c=d#anchor1'); assert(uriFn({uri: '/route?x=y&z=a#anchor1', data:{a:'b', c:'d'}}) === '/route?x=y&z=a&a=b&c=d#anchor1');
assert(dataFn({uri: '/route?x=y&z=a#anchor1', data:{a:'b', c:'d'}}) === undefined); assert(dataFn === undefined);
}); });
}); });
}); });