UNPKG

2.05 kBtext/coffeescriptView Raw
1
2# /*
3# Index
4# */
5# Author: PerterPon<PerterPon@gmail.com>
6# Create: Sat Feb 07 2015 16:26:39 GMT+0800 (CST)
7#
8
9"use strict"
10
11methods = require 'methods'
12pathToRegexp = require './path-to-regexp'
13
14matchMethod = ( 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
21matchPath = ( 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
38create = ( method ) ->
39 method = method.toUpperCase() if method?
40
41 ( path, fn, opt ) ->
42 # trans path to regexp.
43 re = pathToRegexp path, opt
44
45 reqParams = path.match /\:\w+\/?/g
46
47 # erase the '/:' or ':' prefix, and '/' sufix
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 # match method
63 return yield next unless matchMethod req, method
64
65 # match path
66 if true is matchPath req, re, reqParams
67 yield fn req, res, next
68 return
69
70 # miss, to next
71 yield next
72
73 else
74 return ( req, res, next ) ->
75 # match method
76 return next() unless matchMethod req, method
77
78 # match path
79 if true is matchPath req, re, reqParams
80 fn req, res, next
81 return
82
83 # miss, to next
84 next()
85
86methods.forEach ( method ) ->
87 exports[ method ] = create method
88
89exports.all = create()