Skip to content
This repository has been archived by the owner on May 30, 2020. It is now read-only.

Commit

Permalink
[Fix #11] URL generator for dynamic routes redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
sundowndev committed Sep 23, 2018
1 parent e5bbfc1 commit b46e8f4
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 61 deletions.
46 changes: 25 additions & 21 deletions dist/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Router.js
*
* @package @sundowndev/router.js
* @version 1.6.1
* @version 1.6.2
* @description Simple front based mono-page router
* @license MIT
*/
Expand All @@ -19,8 +19,7 @@ var router = function () {
this.notfound = true;
this.routes = [];
this.paramsEnabled = false;
this.routeCall = function () {
};
this.routeCall = function () {};
this.params = [];
this.BeforeRouteMiddleware = '*';
this.BeforeRouteMiddlewareFunc = null;
Expand All @@ -36,7 +35,7 @@ var router = function () {
};

this.notFoundException = function () {
notFoundCallback.apply();
notFoundCallback.apply(null, []);
};

this.getCurrentURI = function () {
Expand Down Expand Up @@ -142,22 +141,35 @@ var router = function () {
}

if (!params) new Exception('Error: route "' + routeName + '" requires some parameters. None specified.');
//let callbackParameters = [];

let generatedURI = this.GenerateURL(targetRoute.route, params);

new RouterRequest().setURI(generatedURI);
};

/**
* @function GenerateURL
*
* Generate URL from route and parameters
*
* @param route
* @param params
* @returns string
*/
this.GenerateURL = function (route, params) {
let generatedURI = route;

for (let p in params) {
if (!params.hasOwnProperty(p)) continue;

const paramInRoute = targetRoute.route.split('/').find(function (targetParam) {
const paramInRoute = route.split('/').find(function (targetParam) {
return targetParam === ':' + p;
});

targetRoute.route = targetRoute.route.replace(paramInRoute, params[p]);
//callbackParameters.push(params[p]);
generatedURI = generatedURI.replace(paramInRoute, params[p]);
}

//console.log(callbackParameters);
//targetRoute.callback.apply(null, callbackParameters);
new RouterRequest().setURI(targetRoute.route);
return generatedURI;
};

/**
Expand Down Expand Up @@ -219,15 +231,11 @@ var router = function () {
return;
}

//console.log(routes);

parent.routes.forEach(function (route) {
if (route.route === Route && parent.notfound) {
setRoute(route, RouteOptions.params);
}
});


});
};

Expand Down Expand Up @@ -256,10 +264,7 @@ var router = function () {
if (route.paramsEnabled) {
routes.push(route.route);
parent.handle(routes);

console.log(routes);
} else if (route.route === URI) {
//console.log(1);
setRoute(route);
}
});
Expand All @@ -280,7 +285,6 @@ var router = function () {

/**
* Listen to the URI
*
* @event hashchange
*/
window.addEventListener('hashchange', function () {
Expand Down Expand Up @@ -340,9 +344,9 @@ const BeforeMiddleware = function (route, callback) {

if (this.callback != null) {
if (this.route === '*') {
this.callback.apply();
this.callback.apply(null, []);
} else if (this.route === this.URI) {
this.callback.apply();
this.callback.apply(null, []);
}
}
};
Expand Down
121 changes: 81 additions & 40 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
/**
* Router.js
*
* @author SundownDEV https://github.com/SundownDEV
* @version 1.5.10
* @package @sundowndev/router.js
* @version 1.6.2
* @description Simple front based mono-page router
* @license MIT
*/
Expand Down Expand Up @@ -37,7 +37,7 @@ var Router = function () {
};

this.notFoundException = function () {
notFoundCallback.apply();
notFoundCallback.apply(null, []);
};

this.getCurrentURI = function () {
Expand Down Expand Up @@ -67,9 +67,13 @@ var Router = function () {
* @param callback function
*/
this.add = function (name, route, callback) {
let routeArray = route.split('/'),
paramsEnabled = false,
params = [];
if (typeof name !== 'string' || typeof route !== 'string' || typeof callback !== 'function') {
new Exception('Error while adding a route. Parameters "name" and "route" must be type of string. Callback must be a valid function.');
}

const routeArray = route.split('/');
let paramsEnabled = false,
params = [];

routeArray.forEach(function (r) {
if (r.substr(0, 1) === ':') {
Expand Down Expand Up @@ -106,6 +110,10 @@ var Router = function () {
* @param routes array
*/
this.map = function (name, mount, routes = []) {
if (typeof name !== 'string' || typeof mount !== 'string' || !Array.isArray(routes)) {
new Exception('Error while adding a route. Parameters "name" and "mount" must be type of string. Routes must be an Array.');
}

routes.forEach(function (route) {
parent.add(name + route.name, mount + parent.FormatPath(route.route, true), route.callback);
});
Expand All @@ -120,19 +128,50 @@ var Router = function () {
* @param params array
*/
this.fetchRoute = function (routeName, params) {
let targetRoute = parent.routes.find(function (route) {
const targetRoute = parent.routes.find(function (route) {
return route.name === routeName || route.route === routeName;
});

if (targetRoute === undefined) {
if (typeof targetRoute !== 'object') {
new Exception('Target route "' + routeName + '" does not exist');
return;
}

if (!targetRoute.paramsEnabled) {
new RouterRequest().setURI(targetRoute.route);
} else if (targetRoute.paramsEnabled) {
new Exception('"' + routeName + '" route has parameter(s) and cannot be call dynamically');
return;
}

if (!params) new Exception('Error: route "' + routeName + '" requires some parameters. None specified.');

let generatedURI = this.GenerateURL(targetRoute.route, params);

new RouterRequest().setURI(generatedURI);
};

/**
* @function GenerateURL
*
* Generate URL from route and parameters
*
* @param route
* @param params
* @returns string
*/
this.GenerateURL = function (route, params) {
let generatedURI = route;

for (let p in params) {
if (!params.hasOwnProperty(p)) continue;

const paramInRoute = route.split('/').find(function (targetParam) {
return targetParam === ':' + p;
});

generatedURI = generatedURI.replace(paramInRoute, params[p]);
}

return generatedURI;
};

/**
Expand Down Expand Up @@ -161,7 +200,7 @@ var Router = function () {
* @param route string
* @param params array
*/
let setRoute = function (route, params = []) {
const setRoute = function (route, params = []) {
parent.route = route;
parent.routeCall = route.callback;
parent.params = params;
Expand All @@ -176,25 +215,29 @@ var Router = function () {
* @param routes array
*/
this.handle = function (routes) {
let URI = parent.getCurrentURI();
const URI = parent.getCurrentURI();

routes.forEach(function (Route) {
let RouteArray = Route.split('/');
const RouteArray = Route.split('/');
let URIarray = URI.split('/');

if (URIarray.length === RouteArray.length) {
let RouteOptions = new handlingParams(Route);
if (URIarray.length !== RouteArray.length) {
return;
}

const RouteOptions = new handlingParams(Route);

URIarray = URIarray.join('');
URIarray = URIarray.join('');

if (RouteOptions.RouteArray === URIarray) {
parent.routes.forEach(function (route) {
if (route.route === Route && parent.notfound) {
setRoute(route, RouteOptions.params);
}
});
}
if (RouteOptions.RouteArray !== URIarray) {
return;
}

parent.routes.forEach(function (route) {
if (route.route === Route && parent.notfound) {
setRoute(route, RouteOptions.params);
}
});
});
};

Expand All @@ -206,8 +249,8 @@ var Router = function () {
* @param AfterRouteCallback function
*/
this.run = function (AfterRouteCallback = null) {
let URI = parent.getCurrentURI();
let routes = [];
const URI = parent.getCurrentURI();
const routes = [];

/**
* While a route has not match the URI, page is not found
Expand All @@ -226,26 +269,24 @@ var Router = function () {
} else if (route.route === URI) {
setRoute(route);
}

});

if (parent.notfound) {
notFoundCallback.apply();
notFoundCallback.apply(null, []);
} else {
parent.routeCall.apply(null, parent.params);
}

if (AfterRouteCallback != null) {
parent.AfterRouteCallback = AfterRouteCallback;
parent.AfterRouteCallback.apply();
parent.AfterRouteCallback.apply(null, []);
} else if (parent.AfterRouteCallback != null) {
parent.AfterRouteCallback.apply();
parent.AfterRouteCallback.apply(null, []);
}
};

/**
* Listen to the URI
*
* @event hashchange
*/
window.addEventListener('hashchange', function () {
Expand All @@ -259,7 +300,7 @@ var Router = function () {
* @function getURI get the current URI
* @function setURI set the current URI
*/
let RouterRequest = function () {
const RouterRequest = function () {
const parent = this;

let URI = '/' + location.hash;
Expand Down Expand Up @@ -287,7 +328,7 @@ let RouterRequest = function () {
* @param route string
* @param callback function
*/
let BeforeMiddleware = function (route, callback) {
const BeforeMiddleware = function (route, callback) {
const parent = this;

this.route = route;
Expand All @@ -305,9 +346,9 @@ let BeforeMiddleware = function (route, callback) {

if (this.callback != null) {
if (this.route === '*') {
this.callback.apply();
this.callback.apply(null, []);
} else if (this.route === this.URI) {
this.callback.apply();
this.callback.apply(null, []);
}
}
};
Expand All @@ -318,12 +359,12 @@ let BeforeMiddleware = function (route, callback) {
* @param route string
* @returns {{ params: Array, RouteArray: string }}
*/
let handlingParams = function (route) {
const handlingParams = function (route) {
const parent = this;

let URIarray = router.getCurrentURI().split('/');
let RouteArray = route.split('/');
let params = [];
const URIarray = router.getCurrentURI().split('/');
const RouteArray = route.split('/');
const params = [];

/**
* Handling route parameters
Expand All @@ -336,7 +377,7 @@ let handlingParams = function (route) {
}
};

for (var i = 0; i < RouteArray.length; i++) {
for (let i = 0; i < RouteArray.length; i++) {
if (RouteArray[i].substr(0, 1) === ':') {
parent.pushParam(URIarray[i]);
RouteArray[i] = URIarray[i];
Expand All @@ -354,7 +395,7 @@ let handlingParams = function (route) {
*
* @param message string
*/
let Exception = function (message) {
const Exception = function (message) {
throw new TypeError(message);
};

Expand Down

0 comments on commit b46e8f4

Please sign in to comment.