Created
February 5, 2014 09:38
-
-
Save peyerluk/8820149 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = class Router | |
constructor: -> | |
@routes = [] | |
get: (path) -> @findRoute('get', path) | |
post: (path, data) -> @findRoute('post', path, data) | |
put: (path, data) -> @findRoute('put', path, data) | |
patch: (path, data) -> @findRoute('patch', path, data) | |
addRoute: (method, route, handler) -> | |
regex = @convertToRegex(route) | |
@routes.push | |
route: route | |
regex: regex | |
method: method.toLowerCase() | |
handler: handler | |
convertToRegex: (route) -> | |
route = route.replace /(:\w+)/, (match) -> | |
'(\\w+)' | |
route = route.replace(/\//g, '\\/') | |
regex = new RegExp(route) | |
findRoute: (method, path) -> | |
console.log path | |
for route in @routes | |
continue if route.method != method.toLowerCase() | |
match = route.regex.exec(path) | |
if match? | |
args = match.slice(1) if match.length > 1 | |
route.handler.apply(this, args) | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment