Skip to content

Instantly share code, notes, and snippets.

@peyerluk
Created February 5, 2014 09:38
Show Gist options
  • Save peyerluk/8820149 to your computer and use it in GitHub Desktop.
Save peyerluk/8820149 to your computer and use it in GitHub Desktop.
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