1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | "use strict"
|
10 |
|
11 | methods = require 'methods'
|
12 | pathToRegexp = require './path-to-regexp'
|
13 |
|
14 | matchMethod = ( req, requiredMethod ) ->
|
15 | { method } = req
|
16 | return true unless requiredMethod?
|
17 | return true if method is requiredMethod
|
18 | return true if 'HEAD' is requiredMethod and 'GET' is method
|
19 | return false
|
20 |
|
21 | matchPath = ( req, re, reqParams ) ->
|
22 |
|
23 | { url, method } = req
|
24 |
|
25 | if m = re.exec url
|
26 | args = m.slice( 1 ).map ( val ) -> decodeURIComponent val if val?
|
27 |
|
28 | req.originatorParam = args
|
29 | if null isnt reqParams
|
30 | params = {}
|
31 | for name, idx in reqParams
|
32 | params[ name ] = args[ idx ]
|
33 | req.params = params
|
34 | true
|
35 | else
|
36 | false
|
37 |
|
38 | create = ( method ) ->
|
39 | method = method.toUpperCase() if method?
|
40 |
|
41 | ( path, fn, opt ) ->
|
42 |
|
43 | re = pathToRegexp path, opt
|
44 |
|
45 | reqParams = path.match /\:\w+\/?/g
|
46 |
|
47 |
|
48 | if null isnt reqParams
|
49 | reqParams = reqParams.map ( val ) ->
|
50 | ff = 0
|
51 | bb = val.length
|
52 | if 0 is val.indexOf '\/\:'
|
53 | ff = 2
|
54 | else if 0 is val.indexOf '\:'
|
55 | ff = 1
|
56 | if val.length - 1 is val.lastIndexOf '\/'
|
57 | bb -= 1
|
58 | val.substring ff, bb
|
59 |
|
60 | if 'GeneratorFunction' is fn.constructor.name
|
61 | return ( req, res, next ) ->
|
62 |
|
63 | return yield next unless matchMethod req, method
|
64 |
|
65 |
|
66 | if true is matchPath req, re, reqParams
|
67 | yield fn req, res, next
|
68 | return
|
69 |
|
70 |
|
71 | yield next
|
72 |
|
73 | else
|
74 | return ( req, res, next ) ->
|
75 |
|
76 | return next() unless matchMethod req, method
|
77 |
|
78 |
|
79 | if true is matchPath req, re, reqParams
|
80 | fn req, res, next
|
81 | return
|
82 |
|
83 |
|
84 | next()
|
85 |
|
86 | methods.forEach ( method ) ->
|
87 | exports[ method ] = create method
|
88 |
|
89 | exports.all = create()
|