UNPKG

2.54 kBJavaScriptView Raw
1// Generated by CoffeeScript 1.7.1
2(function() {
3 var Router, extend, path, urlPattern,
4 __slice = [].slice;
5
6 path = require('path');
7
8 urlPattern = require('url-pattern');
9
10 extend = require('./util').extend;
11
12 Router = (function() {
13 function Router() {
14 this.routes = [];
15 }
16
17 Router.prototype.resource = function(pattern, controller, options) {
18 var dest;
19 dest = function(action) {
20 return [controller, action].join('#');
21 };
22 this.route('GET', pattern, dest('index'), options);
23 this.route('GET', path.join(pattern, ":id"), dest('show'), options);
24 this.route('POST', pattern, dest('create'), options);
25 this.route(['POST', 'PUT', 'PATCH'], path.join(pattern, ":id"), dest('update'), options);
26 return this.route('DELETE', pattern, dest('delete'), options);
27 };
28
29 Router.prototype.route = function(method, pattern, dest, options) {
30 var action, controller, m, _i, _len, _ref, _ref1, _ref2;
31 if (method instanceof Array) {
32 for (_i = 0, _len = method.length; _i < _len; _i++) {
33 m = method[_i];
34 (_ref = this.route).call.apply(_ref, [this, m].concat(__slice.call(Array.prototype.slice.call(arguments, 1))));
35 }
36 return;
37 }
38 if (!dest || typeof dest === 'object') {
39 _ref1 = ['GET', method, pattern, dest], method = _ref1[0], pattern = _ref1[1], dest = _ref1[2], options = _ref1[3];
40 }
41 options || (options = {});
42 options.method = (options.method || method).toUpperCase();
43 options.pattern = urlPattern.newPattern(pattern);
44 if (typeof dest === 'string' && dest.indexOf('#') !== -1) {
45 _ref2 = dest.split('#'), controller = _ref2[0], action = _ref2[1];
46 options.controller = controller;
47 options.action = action;
48 } else if (typeof dest === 'function') {
49 options.fn = dest;
50 } else {
51 throw new Error("Bad destination: " + dest + ". Must be a function or a string like 'Controller#action'");
52 }
53 return this.routes.push(options);
54 };
55
56 Router.prototype.match = function(method, url) {
57 var match, route, _i, _len, _ref;
58 _ref = this.routes;
59 for (_i = 0, _len = _ref.length; _i < _len; _i++) {
60 route = _ref[_i];
61 if (method === route.method && (match = route.pattern.match(url))) {
62 return extend({
63 routeParams: match
64 }, route);
65 }
66 }
67 return false;
68 };
69
70 return Router;
71
72 })();
73
74 module.exports = Router;
75
76}).call(this);