Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created July 28, 2012 16:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandopazo/3193926 to your computer and use it in GitHub Desktop.
Save juandopazo/3193926 to your computer and use it in GitHub Desktop.
Server Y.Router
YUI.add('router', function (Y) {
/**
Provides URL-based routing for Node
@module app
@submodule router
@since 3.4.0
**/
var QS = Y.QueryString,
YArray = Y.Array,
// Holds all the active router instances. This supports the static
// `dispatch()` method which causes all routers to dispatch.
instances = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
protocol: 'http',
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._routes = [];
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish. We're not on the browser so we don't
// need to wait for window.onload or similar stuff
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
});
// Store this router in the collection of all active router instances.
instances.push(this);
},
destructor: function () {
var instanceIndex = Y.Array.indexOf(instances, this);
// Remove this router from the collection of active router instances.
if (instanceIndex > -1) {
instances.splice(instanceIndex, 1);
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function (req, res, next) {
this.once(EVT_READY, function () {
this._ready = true;
this._dispatch(req, res, next);
});
return this;
},
middleware: function () {
var self = this;
return function (req, res, next) {
self._setupRequest(req);
self._setupResponse(res);
if (self.hasRoute(req.url, req.method)) {
self.dispatch(req, res, next);
} else {
next();
}
};
},
/**
Gets the current route path, relative to the `root` (if any).
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this.removeQuery(this._req.url);
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise.
The URL accepted is the Node url without the host and protocol
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url, method) {
return !!this.match(this.removeQuery(url), method).length;
},
/**
Returns an array of route objects that match the specified URL path.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match.
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path, method) {
return this._routes.filter(function (route) {
var matches = path.search(route.regex) > -1;
if (matches && route.method && route.method != method) {
matches = false;
}
return matches;
});
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root');
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
if (root && url.indexOf(root) === 0) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Removes a query string from the end of the _url_ (if one exists) and returns
the result.
@method removeQuery
@param {String} url URL.
@return {String} Queryless path.
**/
removeQuery: function (url) {
return url.replace(/\?.*$/, '');
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._redirect(url, 302);
},
/**
Adds a route handler for the specified URL _path_.
The _path_ parameter may be either a string or a regular expression. If it's
a string, it may contain named parameters: `:param` will match any single
part of a URL path (not including `/` characters), and `*param` will match
any number of parts of a URL path (including `/` characters). These named
parameters will be made available as keys on the `req.params` object that's
passed to route handlers.
If the _path_ parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
If multiple route handlers match a given URL, they will be executed in the
order they were added. The first route that was added will be the first to
be executed.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
Y.log('Current tag: ' + req.params.tag);
Y.log('Current page number: ' + req.params.page);
});
@method route
@param {String|RegExp} path Path to match. May be a string or a regular
expression.
@param {Function|String} callback Callback function to call whenever this
route is triggered. If specified as a string, the named function will be
called on this router instance.
@param {Object} callback.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callback.req.params Captured parameters matched by
the route path specification. If a string path was used and contained
named parameters, then this will be a key/value hash mapping parameter
names to their matched values. If a regex path was used, this will be
an array of subpattern matches starting at index 0 for the full match,
then 1 for the first subpattern match, and so on.
@param {String} callback.req.path The current URL path.
@param {Number} callback.req.pendingRoutes Number of matching routes
after this one in the dispatch chain.
@param {Object} callback.req.query Query hash representing the URL query
string, if any. Parameter names are keys, and are mapped to parameter
values.
@param {String} callback.req.url The full URL.
@param {String} callback.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate".
@param {Object} callback.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callback.res.req Reference to the request object.
@param {Function} callback.next Callback to pass control to the next
matching route. If you don't call this function, then no further route
handlers will be executed, even if there are more that match. If you do
call this function, then the next matching route handler (if any) will
be called, and will receive the same `req` object that was passed to
this route (so you can use the request object to pass data along to
subsequent routes).
@chainable
**/
route: function (path, callback) {
return this._route(path, 'GET', callback);
},
post: function (path, callback) {
return this._route(path, 'POST', callback);
},
put: function (path, callback) {
return this._route(path, 'PUT', callback);
},
delete: function (path, callback) {
return this._route(path, 'DELETE', callback);
},
head: function (path, callback) {
return this._route(path, 'HEAD', callback);
},
all: function (path, callback) {
return this._route(path, undefined, callback);
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
navigate: function (url) {
return this._redirect(url, 204);
},
// -- Protected Methods ----------------------------------------------------
_route: function (path, method, callback) {
var keys = [];
this._routes.push({
callback: callback,
keys : keys,
path : path,
method : method,
regex : this._getRegex(path, keys)
});
return this;
},
/**
@method _redirect
@chainable
@protected
*/
_redirect: function (url, statusCode) {
var res = this._getResponse();
res.writeHead(statusCode, {
Location: url
});
res.end();
return this;
},
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {String} path URL path.
@param {String} url Full URL.
@param {String} src What initiated the dispatch.
@chainable
@protected
**/
_dispatch: function (req, res, next, src) {
var self = this,
path = req.path,
routes = self.match(path, req.method);
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
req.src = src;
req.next = function (err) {
var callback, matches, route;
if (err) {
next(err);
} else if ((route = routes.shift())) {
matches = route.regex.exec(path);
callback = typeof route.callback === 'string' ?
self[route.callback] : route.callback;
// Use named keys for parameter names if the route path contains
// named keys. Otherwise, use numerical match indices.
if (matches.length === route.keys.length + 1) {
req.params = YArray.hash(route.keys, matches.slice(1));
} else {
req.params = matches.concat();
}
req.pendingRoutes = routes.length;
callback.call(self, req, res, req.next);
}
};
req.next();
self._dispatching = false;
return self;
},
_setupResponse: function (res) {},
_setupRequest: funciton (req) {
req.path = this.removeQuery(req.url);
req.query = this._parseQuery(this._getQuery(req.url));
},
/**
Returns the current path root after popping off the last path segment,
making it useful for resolving other URL paths against.
The path root will always begin and end with a '/'.
@method _getPathRoot
@return {String} The URL's path root.
@protected
@since 3.5.0
**/
_getPathRoot: function () {
var slash = '/',
path = this.getPath(),
segments;
if (path.charAt(path.length - 1) === slash) {
return path;
}
segments = path.split(slash);
segments.pop();
return segments.join(slash) + slash;
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function (location) {
var queryStart = location.indexOf('?');
return queryStart > -1 ? location.substr(queryStart + 1) : '';
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (path instanceof RegExp) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/#?]*)';
});
return new RegExp('^' + path + '$');
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = this.protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
// Causes `url` to _always_ begin with a "/".
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Returns a normalized path, ridding it of any '..' segments and properly
handling leading and trailing slashes.
@method _normalizePath
@param {String} path URL path to normalize.
@return {String} Normalized path.
@protected
@since 3.5.0
**/
_normalizePath: function (path) {
var dots = '..',
slash = '/',
i, len, normalized, segments, segment, stack;
if (!path || path === slash) {
return slash;
}
segments = path.split(slash);
stack = [];
for (i = 0, len = segments.length; i < len; ++i) {
segment = segments[i];
if (segment === dots) {
stack.pop();
} else if (segment) {
stack.push(segment);
}
}
normalized = slash + stack.join(slash);
// Append trailing slash if necessary.
if (normalized !== slash && path.charAt(path.length - 1) === slash) {
normalized += slash;
}
return normalized;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
routes.forEach(function (route) {
this._route(route.path, route.method, route.callback);
}, this);
return this._routes.concat();
},
// -- Protected Event Handlers ---------------------------------------------
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callback`: Function or a string representing the name of a function
on this router instance that should be called when the route is
triggered. See the docs for the `route()` method for more details.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// To make this testable.
_instances: instances,
/**
Dispatches to the first route handler that matches the specified `path` for
all active router instances.
This provides a mechanism to cause all active router instances to dispatch
to their route handlers.
This method should be called from each request made to the server
@method dispatch
@static
@param [ServerRquest] request
@param [ServerResponse] response
@returns [Boolean] true if any route matched
@since 3.6.0
**/
dispatch: function (req, res) {
var i, len, router,
routed = false;
for (i = 0, len = instances.length; i < len; i += 1) {
router = instances[i];
if (router) {
if (!routed && router.hasRoute(req.url, req.method)) {
routed = true;
}
router._dispatch(req, res);
}
}
return routed;
}
});
}, '0.0.1', { requires: ['base', 'querystring'] });
@juandopazo
Copy link
Author

To do:

  • Figure out what to do with protocol
  • Document
  • Write at least one example

@juandopazo
Copy link
Author

Basic usage:

  • Install YUI npm install yui
  • Add the module to the YUI config
  • Use it with Connect or a simple HTTP server:

HTTP server:

var http = require('http'),
  YUI = require('yui').YUI,
  Y = YUI(someConfig).use('router');

http.createServer(function (req, res) {
  Y.Router.dispatch(req, res);
}).listen(80);

var router = new Y.Router();
router.route('/foo', function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello world\n');
});

Connect:

var connect = require('connect'),
  YUI = require('yui').YUI,
  Y = YUI(someConfig).use('router'),
  app = connect();

app.use(connect.static());
app.use(Y.Router.middleware);

var router = new Y.Router();
router.route('/foo', function (req, res) {
  res.header('Content-Type': 'text/plain');
  res.send('Hello world\n');
});

app.listen(80);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment