Last active
July 29, 2017 13:19
-
-
Save Kamilczak020/9a9bbc7971f2d187970c968978e1a8bb to your computer and use it in GitHub Desktop.
Basic NodeJS router
This file contains 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
var url = require('url'); | |
var Router = function() { | |
this.handlers = []; | |
this.add = add; | |
this.match = match; | |
this.handleInvalidRoute = handleInvalidRoute; | |
} | |
var Handler = function(path, method) { | |
this.route = new Route(path); | |
this.method = method; | |
} | |
const Route = function(path) { | |
let segments = path.split('/') | |
.map((segment, index) => ({name: segment, index: index - 1})) | |
.filter(({ name }) => name !== ''); | |
this.segments = segments; | |
} | |
let add = function(url, method) { | |
this.handlers.push(new Handler(url, method)); | |
} | |
let match = function(request, response) { | |
let queryRoute = new Route(request.url); | |
let handlers = this.handlers; | |
let originalRequestObject = request; | |
for (let i = 0; i < handlers.length; i++) { | |
if (handlers[i].route.segments.length !== queryRoute.segments.length) continue; | |
for (let j = 0; j < handlers[i].route.segments.length; j++) { | |
if (handlers[i].route.segments[j].name[0] !== ":" && | |
JSON.stringify(handlers[i].route.segments[j]) !== JSON.stringify(queryRoute.segments[j])) | |
break; | |
if (handlers[i].route.segments[j].name[0] === ":") { | |
let param = handlers[i].route.segments[j]; | |
let paramIndex = handlers[i].route.segments[j].index; | |
let queryParam = queryRoute.segments[paramIndex]; | |
request[param.name.substr(1)] = queryParam.name; | |
} | |
// Is a last segment and was correct, so we have a match | |
if (j === handlers[i].route.segments.length - 1) | |
return handlers[i].method(request, response); | |
} | |
} | |
// We are passing an original request object, so that it doesn't contain any new objects that were added. | |
return this.handleInvalidRoute(originalRequestObject, response); | |
} | |
let handleInvalidRoute = function(request, response) { | |
response.writeHead(404, {'Content-Type': 'text/plain'}); | |
response.write("The provided URL is invalid! : " + request.url); | |
response.end(); | |
} | |
module.exports = Router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment