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
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) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.frontexpress = factory());
}(this, (function () { 'use strict';
var frontexpress = (function () {
'use strict';
/**
* HTTP method list
* @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) {
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) {
set$1(parent, property, value, receiver);
var slicedToArray = function () {
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) {
setter.call(receiver, value);
}
return _arr;
}
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) {
var _this = this;
var method = request.method;
var uri = request.uri;
var headers = request.headers;
var data = request.data;
var method = request.method,
uri = request.uri,
headers = request.headers,
data = request.data;
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 status = _ref.status;
var statusText = _ref.statusText;
var errorThrown = _ref.errorThrown;
var status = _ref.status,
statusText = _ref.statusText,
errorThrown = _ref.errorThrown;
var errors = _this._analyzeErrors({ status: status, statusText: statusText, errorThrown: errorThrown });
reject(request, { status: status, statusText: statusText, errorThrown: errorThrown, errors: errors });
// Removed for reducing size of frontexpress
// const errors = this._analyzeErrors({status, statusText, errorThrown});
reject(request, {
status: status,
statusText: statusText,
errorThrown: errorThrown,
errors: 'HTTP ' + status + ' ' + (statusText ? statusText : '')
});
};
var xmlhttp = new XMLHttpRequest();
@ -198,47 +221,47 @@ var Requester = function () {
}
}
/**
* Analyse response errors.
*
* @private
*/
// Removed for reducing size of frontexpress
// /**
// * Analyse response errors.
// *
// * @private
// */
}, {
key: '_analyzeErrors',
value: function _analyzeErrors(response) {
// manage exceptions
if (response.errorThrown) {
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 exceptions
// if (response.errorThrown) {
// 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;
// }
// // 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;
}();
@ -272,40 +295,30 @@ var Settings = function () {
'http GET transformer': {
uri: function uri(_ref) {
var _uri = _ref.uri;
var headers = _ref.headers;
var data = _ref.data;
var _uri = _ref.uri,
headers = _ref.headers,
data = _ref.data;
if (!data) {
return _uri;
}
var uriWithoutAnchor = _uri,
anchor = '';
var anchor = '';
var uriWithoutAnchor = _uri;
var hashIndex = _uri.indexOf('#');
if (hashIndex >= 1) {
uriWithoutAnchor = _uri.slice(0, hashIndex);
anchor = _uri.slice(hashIndex, _uri.length);
var match = /^(.*)(#.*)$/.exec(_uri);
if (match) {
var _$exec = /^(.*)(#.*)$/.exec(_uri);
var _$exec2 = slicedToArray(_$exec, 3);
uriWithoutAnchor = _$exec2[1];
anchor = _$exec2[2];
}
uriWithoutAnchor = Object.keys(data).reduce(function (gUri, d, index) {
if (index === 0 && gUri.indexOf('?') === -1) {
gUri += '?';
} else {
gUri += '&';
}
gUri += d + '=' + data[d];
gUri += '' + (index === 0 && gUri.indexOf('?') === -1 ? '?' : '&') + d + '=' + data[d];
return gUri;
}, uriWithoutAnchor);
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, [{
key: 'set',
value: function set(name, value) {
value: function set$$1(name, value) {
var checkRules = this.rules[name];
if (checkRules) {
checkRules(value);
@ -346,7 +359,7 @@ var Settings = function () {
}, {
key: 'get',
value: function get(name) {
value: function get$$1(name) {
return this.settings[name];
}
}]);
@ -367,7 +380,7 @@ var Middleware = function () {
*/
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);
this.name = name;
@ -384,66 +397,61 @@ var Middleware = function () {
* @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, [{
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',
value: function next() {
return true;
@ -488,7 +496,7 @@ var Route = function () {
createClass(Route, [{
key: 'uri',
get: function get() {
get: function get$$1() {
if (!this.uriPart && !this.method) {
return undefined;
}
@ -709,7 +717,7 @@ var Router = function () {
}
}, {
key: 'baseUri',
set: function set(uri) {
set: function set$$1(uri) {
if (!uri) {
return;
}
@ -735,7 +743,7 @@ var Router = function () {
*/
,
get: function get() {
get: function get$$1() {
return this._baseUri;
}
}]);
@ -868,20 +876,19 @@ var Application = function () {
createClass(Application, [{
key: 'set',
value: function set() {
value: function set$$1() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// get behaviour
if (args.length === 1) {
var _name = [args];
return this.settings.get(_name);
return this.settings.get([args]);
}
// set behaviour
var name = args[0];
var value = args[1];
var name = args[0],
value = args[1];
this.settings.set(name, value);
@ -910,19 +917,19 @@ var Application = function () {
var _this = this;
window.onbeforeunload = function () {
_this._callMiddlewareExited();
_this._callMiddlewareMethod('exited');
};
window.onpopstate = function (event) {
if (event.state) {
var _event$state = event.state;
var request = _event$state.request;
var response = _event$state.response;
var _event$state = event.state,
request = _event$state.request,
response = _event$state.response;
var currentRoutes = _this._routes(request.uri, request.method);
_this._callMiddlewareEntered(currentRoutes, request);
_this._callMiddlewareUpdated(currentRoutes, request, response);
_this._callMiddlewareMethod('entered', currentRoutes, request);
_this._callMiddlewareMethod('updated', currentRoutes, request, response);
}
};
@ -933,14 +940,14 @@ var Application = function () {
// DOM state
if (document.readyState === 'loading' && !_this.isDOMLoaded) {
_this.isDOMLoaded = true;
_this._callMiddlewareEntered(currentRoutes, request);
_this._callMiddlewareMethod('entered', currentRoutes, request);
} else if (document.readyState === 'interactive' && !_this.isDOMReady) {
if (!_this.isDOMLoaded) {
_this.isDOMLoaded = true;
_this._callMiddlewareEntered(currentRoutes, request);
_this._callMiddlewareMethod('entered', currentRoutes, request);
}
_this.isDOMReady = true;
_this._callMiddlewareUpdated(currentRoutes, request, response);
_this._callMiddlewareMethod('updated', currentRoutes, request, response);
if (callback) {
callback(request, response);
}
@ -993,30 +1000,24 @@ var Application = function () {
args[_key2] = arguments[_key2];
}
if (args.length === 0) {
throw new TypeError('use method takes at least a middleware or a router');
}
var errorMsg = 'use method takes at least a middleware or a router';
var baseUri = void 0,
middleware = void 0,
router = void 0,
which = void 0;
if (args.length === 1) {
if (!args || args.length === 0) {
throw new TypeError(errorMsg);
} else if (args.length === 1) {
which = args[0];
} else {
baseUri = args[0];
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) {
router = which;
router.baseUri = baseUri;
} else {
} else if (which instanceof Middleware || typeof which === 'function') {
middleware = which;
router = new Router(baseUri);
var _iteratorNormalCompletion = true;
@ -1043,6 +1044,8 @@ var Application = function () {
}
}
}
} else {
throw new TypeError(errorMsg);
}
this.routers.push(router);
@ -1059,8 +1062,8 @@ var Application = function () {
}, {
key: '_routes',
value: function _routes() {
var uri = arguments.length <= 0 || arguments[0] === undefined ? window.location.pathname + window.location.search : arguments[0];
var method = arguments.length <= 1 || arguments[1] === undefined ? 'GET' : arguments[1];
var uri = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.pathname + window.location.search;
var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GET';
var currentRoutes = [];
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) {
var router = _step2.value;
var routes = router.routes(uri, method);
currentRoutes.push.apply(currentRoutes, toConsumableArray(routes));
currentRoutes.push.apply(currentRoutes, toConsumableArray(router.routes(uri, method)));
}
} catch (err) {
_didIteratorError2 = true;
@ -1093,146 +1095,95 @@ var Application = function () {
}
/**
* Call `Middleware#entered` on _currentRoutes_.
* Invoked before sending ajax request or when DOM
* is loading (document.readyState === 'loading').
* Call `Middleware` method or middleware function on _currentRoutes_.
*
* @private
*/
}, {
key: '_callMiddlewareEntered',
value: function _callMiddlewareEntered(currentRoutes, request) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
key: '_callMiddlewareMethod',
value: function _callMiddlewareMethod(meth, currentRoutes, request, response) {
if (meth === 'exited') {
// currentRoutes, request, response params not needed
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 {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
for (var _iterator3 = this.routers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var router = _step3.value;
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
/**
* Call `Middleware#updated` or middleware function on _currentRoutes_.
* Invoked on ajax request responding or on DOM ready
* (document.readyState === 'interactive').
*
* @private
*/
try {
for (var _iterator4 = router.visited()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var route = _step4.value;
}, {
key: '_callMiddlewareUpdated',
value: function _callMiddlewareUpdated(currentRoutes, request, response) {
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = currentRoutes[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var route = _step4.value;
route.visited = request;
// calls middleware updated method
if (route.middleware.updated) {
route.middleware.updated(request, response);
if (route.middleware.next && !route.middleware.next()) {
break;
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
} else {
// calls middleware method
var breakMiddlewareLoop = true;
var next = function next() {
breakMiddlewareLoop = false;
};
route.middleware(request, response, next);
if (breakMiddlewareLoop) {
break;
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
return;
}
}
/**
* 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 _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = this.routers[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var router = _step5.value;
for (var _iterator5 = currentRoutes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var _route = _step5.value;
var routes = router.visited();
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
if (meth === 'updated') {
_route.visited = request;
}
try {
for (var _iterator6 = routes[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var route = _step6.value;
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
if (_route.middleware[meth]) {
_route.middleware[meth](request, response);
if (_route.middleware.next && !_route.middleware.next()) {
break;
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
} else if (meth !== 'entered') {
// calls middleware method
var breakMiddlewareLoop = true;
var next = function next() {
breakMiddlewareLoop = false;
};
_route.middleware(request, response, next);
if (breakMiddlewareLoop) {
break;
}
}
}
@ -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.
*
@ -1315,11 +1214,11 @@ var Application = function () {
value: function _fetch(request, resolve, reject) {
var _this2 = this;
var method = request.method;
var uri = request.uri;
var headers = request.headers;
var data = request.data;
var history = request.history;
var method = request.method,
uri = request.uri,
headers = request.headers,
data = request.data,
history = request.history;
var httpMethodTransformer = this.get('http ' + method + ' transformer');
@ -1330,25 +1229,25 @@ var Application = function () {
}
// calls middleware exited method
this._callMiddlewareExited();
this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri
var currentRoutes = this._routes(uri, method);
// calls middleware entered method
this._callMiddlewareEntered(currentRoutes, request);
this._callMiddlewareMethod('entered', currentRoutes, request);
// invokes http request
this.settings.get('http requester').fetch(request, function (req, res) {
if (history) {
window.history.pushState({ request: req, response: res }, history.title, history.uri);
}
_this2._callMiddlewareUpdated(currentRoutes, req, res);
_this2._callMiddlewareMethod('updated', currentRoutes, req, res);
if (resolve) {
resolve(req, res);
}
}, function (req, res) {
_this2._callMiddlewareFailed(currentRoutes, req, res);
_this2._callMiddlewareMethod('failed', currentRoutes, req, res);
if (reject) {
reject(req, res);
}
@ -1388,26 +1287,17 @@ HTTP_METHODS.reduce(function (reqProto, method) {
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,
middleware = void 0,
which = void 0;
if (args.length === 1) {
if (!args || args.length === 0) {
throw new TypeError(middlewareMethodName + ' method takes at least a middleware ' + (middlewareMethodName === 'get' ? 'or a string' : ''));
} else if (args.length === 1) {
which = args[0];
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
} else {
baseUri = args[0];
which = args[1];
@ -1417,8 +1307,8 @@ HTTP_METHODS.reduce(function (reqProto, method) {
throw new TypeError(middlewareMethodName + ' method takes at least a middleware');
}
var router = new Router();
middleware = which;
var router = new Router();
router[middlewareMethodName](baseUri, middleware);
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();
reqProto[httpMethodName] = function (request, resolve, reject) {
var uri = request.uri;
var headers = request.headers;
var data = request.data;
var history = request.history;
var uri = request.uri,
headers = request.headers,
data = request.data,
history = request.history;
if (!uri) {
uri = request;
@ -1489,10 +1379,8 @@ var frontexpress = function frontexpress() {
frontexpress.Router = function (baseUri) {
return new Router(baseUri);
};
frontexpress.Middleware = function (name) {
return new Middleware(name);
};
frontexpress.Middleware = Middleware;
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) {
// get behaviour
if (args.length === 1) {
const name = [args];
return this.settings.get(name);
return this.settings.get([args]);
}
// set behaviour
@ -78,7 +77,7 @@ export default class Application {
listen(callback) {
window.onbeforeunload = () => {
this._callMiddlewareExited();
this._callMiddlewareMethod('exited');
};
window.onpopstate = (event) => {
@ -86,8 +85,8 @@ export default class Application {
const {request, response} = event.state;
const currentRoutes = this._routes(request.uri, request.method);
this._callMiddlewareEntered(currentRoutes, request);
this._callMiddlewareUpdated(currentRoutes, request, response);
this._callMiddlewareMethod('entered', currentRoutes, request);
this._callMiddlewareMethod('updated', currentRoutes, request, response);
}
};
@ -98,14 +97,14 @@ export default class Application {
// DOM state
if (document.readyState === 'loading' && !this.isDOMLoaded) {
this.isDOMLoaded = true;
this._callMiddlewareEntered(currentRoutes, request);
this._callMiddlewareMethod('entered', currentRoutes, request);
} else if (document.readyState === 'interactive' && !this.isDOMReady) {
if (!this.isDOMLoaded) {
this.isDOMLoaded = true;
this._callMiddlewareEntered(currentRoutes, request);
this._callMiddlewareMethod('entered', currentRoutes, request);
}
this.isDOMReady = true;
this._callMiddlewareUpdated(currentRoutes, request, response);
this._callMiddlewareMethod('updated', currentRoutes, request, response);
if (callback) {
callback(request, response);
}
@ -152,31 +151,27 @@ export default class Application {
*/
use(...args) {
if (args.length === 0) {
throw new TypeError('use method takes at least a middleware or a router');
}
const errorMsg = 'use method takes at least a middleware or a router';
let baseUri, middleware, router, which;
if (args.length === 1) {
if (!args || args.length === 0) {
throw new TypeError(errorMsg);
} else if (args.length === 1) {
[which,] = args;
} else {
[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) {
router = which;
router.baseUri = baseUri;
} else {
} else if ((which instanceof Middleware) || (typeof which === 'function')) {
middleware = which;
router = new Router(baseUri);
for (const method of HTTP_METHODS) {
router[method.toLowerCase()](middleware);
}
} else {
throw new TypeError(errorMsg);
}
this.routers.push(router);
@ -194,8 +189,7 @@ export default class Application {
_routes(uri=window.location.pathname + window.location.search, method='GET') {
const currentRoutes = [];
for (const router of this.routers) {
const routes = router.routes(uri, method);
currentRoutes.push(...routes);
currentRoutes.push(...router.routes(uri, method));
}
return currentRoutes;
@ -203,95 +197,37 @@ export default class Application {
/**
* Call `Middleware#entered` on _currentRoutes_.
* Invoked before sending ajax request or when DOM
* is loading (document.readyState === 'loading').
* Call `Middleware` method or middleware function on _currentRoutes_.
*
* @private
*/
_callMiddlewareEntered(currentRoutes, request) {
for (const route of currentRoutes) {
if (route.middleware.entered) {
route.middleware.entered(request);
}
if (route.middleware.next && !route.middleware.next()) {
break;
_callMiddlewareMethod(meth, currentRoutes, request, response) {
if (meth === 'exited') {
// currentRoutes, request, response params not needed
for (const router of this.routers) {
for (const route of router.visited()) {
if (route.middleware.exited) {
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) {
route.visited = request;
// calls middleware updated method
if (route.middleware.updated) {
route.middleware.updated(request, response);
if (meth === 'updated') {
route.visited = request;
}
if (route.middleware[meth]) {
route.middleware[meth](request, response);
if (route.middleware.next && !route.middleware.next()) {
break;
}
} else {
// 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
} else if (meth !== 'entered') {
// calls middleware method
let breakMiddlewareLoop = true;
const next = () => {
breakMiddlewareLoop = false;
@ -322,13 +258,13 @@ export default class Application {
}
// calls middleware exited method
this._callMiddlewareExited();
this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri
const currentRoutes = this._routes(uri, method);
// calls middleware entered method
this._callMiddlewareEntered(currentRoutes, request);
this._callMiddlewareMethod('entered', currentRoutes, request);
// invokes http request
this.settings.get('http requester').fetch(request,
@ -336,13 +272,13 @@ export default class Application {
if (history) {
window.history.pushState({request: req, response: res}, history.title, history.uri);
}
this._callMiddlewareUpdated(currentRoutes, req, res);
this._callMiddlewareMethod('updated', currentRoutes, req, res);
if (resolve) {
resolve(req, res);
}
},
(req, res) => {
this._callMiddlewareFailed(currentRoutes, req, res);
this._callMiddlewareMethod('failed', currentRoutes, req, res);
if (reject) {
reject(req, res);
}
@ -377,23 +313,14 @@ HTTP_METHODS.reduce((reqProto, method) => {
const middlewareMethodName = method.toLowerCase();
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;
if (args.length === 1) {
[which,] = args;
if (!args || args.length === 0) {
throw new TypeError(`${middlewareMethodName} method takes at least a middleware ${middlewareMethodName === 'get' ? 'or a string' : ''}`);
} else if (args.length === 1) {
[which] = args;
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
} else {
[baseUri, which,] = args;
}
@ -402,8 +329,8 @@ HTTP_METHODS.reduce((reqProto, method) => {
throw new TypeError(`${middlewareMethodName} method takes at least a middleware`);
}
const router = new Router();
middleware = which;
const router = new Router();
router[middlewareMethodName](baseUri, middleware);
this.routers.push(router);
@ -447,4 +374,4 @@ HTTP_METHODS.reduce((reqProto, method) => {
};
return reqProto;
}, Application.prototype);
}, Application.prototype);

View File

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

View File

@ -3,4 +3,6 @@
* @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
*/
entered(request) { }
// entered(request) { }
/**
@ -40,7 +40,7 @@ export default class Middleware {
* @public
*/
exited(request) { }
// exited(request) { }
/**
@ -55,7 +55,7 @@ export default class Middleware {
* @public
*/
updated(request, response) { }
// updated(request, response) { }
/**
@ -67,7 +67,7 @@ export default class Middleware {
* @param {Object} response
* @public
*/
failed(request, response) { }
// failed(request, response) { }
/**

View File

@ -20,15 +20,25 @@ export default class Requester {
const success = (responseText) => {
resolve(
request,
{status: 200, statusText: 'OK', responseText}
{
status: 200,
statusText: 'OK',
responseText
}
);
};
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(
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
// */
/**
* Analyse response errors.
*
* @private
*/
// _analyzeErrors(response) {
// // manage exceptions
// if (response.errorThrown) {
// 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 exceptions
if (response.errorThrown) {
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;
}
// 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:''}`;
// }
}

View File

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

View File

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

View File

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

View File

@ -1,14 +1,28 @@
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-js';
import babel from 'rollup-plugin-babel';
export default {
entry: 'lib/frontexpress.js',
format: 'umd',
format: 'iife',
sourceMap: true,
moduleName:'frontexpress',
plugins: [babel({
babelrc: false,
presets: ['es2015-rollup']
}), uglify()],
dest: 'frontexpress.min.js'
};
dest: 'frontexpress.min.js',
plugins: [
babel({
babelrc: false,
// 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';
describe('Application', () => {
class MyMiddleware extends frontexpress.Middleware {
entered() {}
exited() {}
failed() {}
updated() {}
}
let requester;
describe('generated methods', () => {
@ -65,7 +72,7 @@ describe('Application', () => {
// const spy_pushState = sinon.spy(window.history, 'pushState');
// const app = frontexpress();
// const m = frontexpress.Middleware();
// const m = new MyMiddleware();
// const spy_middleware = sinon.stub(m, 'updated');
// app.set('http requester', requester);
@ -146,7 +153,7 @@ describe('Application', () => {
it('with middleware object readyState===loading', (done) => {
const app = frontexpress();
const m = frontexpress.Middleware();
const m = new MyMiddleware();
sinon.stub(m, 'entered', () => {
done();
});
@ -161,7 +168,7 @@ describe('Application', () => {
it('with middleware object readyState===interactive', (done) => {
const app = frontexpress();
const m = frontexpress.Middleware();
const m = new MyMiddleware();
sinon.stub(m, 'updated', () => {
done();
});
@ -176,7 +183,7 @@ describe('Application', () => {
it('with middleware object event beforeunload', (done) => {
const app = frontexpress();
const m = frontexpress.Middleware();
const m = new MyMiddleware();
sinon.stub(m, 'exited', () => {
done();
});
@ -205,7 +212,7 @@ describe('Application', () => {
const spy_pushState = sinon.spy(window.history, 'pushState');
const app = frontexpress();
const m = frontexpress.Middleware();
const m = new MyMiddleware();
const spy_middleware = sinon.stub(m, 'updated', (req, res) => {
historyObj = req.history;
});
@ -252,7 +259,7 @@ describe('Application', () => {
const spy_pushState = sinon.spy(window.history, 'pushState');
const app = frontexpress();
const m = frontexpress.Middleware();
const m = new MyMiddleware();
const spy_middleware = sinon.stub(m, 'updated', (req, res) => {
historyObj = req.history;
});
@ -404,7 +411,7 @@ describe('Application', () => {
});
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 app = frontexpress();
@ -422,7 +429,7 @@ describe('Application', () => {
});
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 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 app = frontexpress();
@ -505,7 +512,7 @@ describe('Application', () => {
});
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 app = frontexpress();
@ -528,12 +535,12 @@ describe('Application', () => {
it('use two routers', (done)=> {
const router1 = frontexpress.Router();
const m1 = frontexpress.Middleware();
const m1 = new MyMiddleware();
const spy1 = sinon.spy(m1, 'updated');
router1.get('/subroute1', m1);
const router2 = frontexpress.Router();
const m2 = frontexpress.Middleware();
const m2 = new MyMiddleware();
const spy2 = sinon.spy(m2, 'updated');
router2.get('/subroute2', m2);
@ -621,7 +628,7 @@ describe('Application', () => {
});
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 app = frontexpress();
@ -639,7 +646,7 @@ describe('Application', () => {
});
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 app = frontexpress();
@ -801,7 +808,7 @@ describe('Application', () => {
const app = frontexpress();
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_updated = sinon.spy(getMiddleware, 'updated');
const spy_get_exited = sinon.spy(getMiddleware, 'exited');
@ -829,17 +836,17 @@ describe('Application', () => {
const app = frontexpress();
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_updated = sinon.spy(allMiddleware, 'updated');
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_updated = sinon.spy(getMiddleware, 'updated');
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_updated = sinon.spy(postMiddleware, 'updated');
const spy_post_exited = sinon.spy(postMiddleware, 'exited');
@ -912,7 +919,7 @@ describe('Application', () => {
const app = frontexpress();
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');
@ -931,10 +938,10 @@ describe('Application', () => {
const app = frontexpress();
app.set('http requester', requester);
const m1 = frontexpress.Middleware('m1');
const m2 = frontexpress.Middleware('m2');
const m1 = new MyMiddleware('m1');
const m2 = new MyMiddleware('m2');
m2.next = () => false;
const m3 = frontexpress.Middleware('m3');
const m3 = new MyMiddleware('m3');
const spy_m1 = sinon.spy(m1, 'updated');
const spy_m2 = sinon.spy(m2, 'updated');

View File

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

View File

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

View File

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

View File

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