UNPKG

2.03 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Shortcuts plugin.
5 * Provides syntactic sugar for router.
6 *
7 * Crixalis
8 * .plugin('shortcuts', ['get', 'post']);
9 * .router()
10 * .get('/api/info', function () {
11 * ...
12 * })
13 *
14 * .from(/^\/pub\/(.*)$/)
15 * .via('GET', 'HEAD')
16 * .to(function () {
17 * ...
18 * })
19 *
20 * .from('/signin')
21 * .post()
22 * .to(signin);
23 *
24 * @module Crixalis
25 * @submodule shortcuts
26 * @for Controller
27 */
28
29module.exports = function (methods) {
30 var Route = this.router().constructor.prototype;
31
32 if (null == methods) {
33 methods = ['GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'ANY'];
34 }
35
36 if (!Array.isArray(methods)) {
37 throw new Error('Array expected');
38 }
39
40 Route.via = function () {
41 var argv = [].slice.call(arguments);
42
43 if (!argv.length) {
44 throw new Error('Method expected');
45 }
46
47 if (Array.isArray(argv[0])) {
48 if (argv.length > 1) {
49 throw new Error('Unexpected arguments');
50 }
51
52 argv = argv[0];
53
54 if (!argv.length) {
55 argv = undefined;
56 }
57 }
58
59 this.set('methods', argv);
60
61 return this;
62 };
63
64 methods.forEach(function (method) {
65 method = String(method).toLowerCase();
66
67 Route[method] = function (options, callback) {
68 var argv = [].slice.call(arguments);
69
70 /* Get route source */
71 switch (typeof argv[0]) {
72 case 'object':
73 if (!(argv[0] instanceof RegExp)) {
74 break;
75 }
76 case 'string':
77 this.from(argv.shift());
78 break;
79 }
80
81 /* Get route options */
82 if (typeof argv[0] === 'object') {
83 this.set(argv.shift());
84 }
85
86 /* Set route method */
87 if (method === 'any') {
88 this.unset('methods');
89 } else {
90 this.via(method.toUpperCase());
91 }
92
93 /* Set route destination */
94 if (typeof argv[0] === 'function') {
95 this.to(argv.shift());
96 }
97
98 /* Check trailing arguments */
99 if (argv.length) {
100 throw new Error('Unexpected arguments');
101 }
102
103 return this;
104 };
105 });
106};