Created
December 18, 2018 10:32
-
-
Save evanxg852000/2edc52d34fdefa2efc520d52841900c0 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
class Router { | |
... | |
_dispatch(request, response){ | |
let match, handledRequest = false, {url} = request | |
for(let route of this._routes){ | |
// 1- Keep trying till we find a match | |
match = url.match(route.regex) | |
if(match === null || !route.methods.includes(request.method)){ | |
continue | |
} | |
// 2- Collect route params value when match found | |
match = match.filter(item => { | |
return !item || !item.startsWith('/') | |
}) | |
request.params = route.params.reduce((obj, param, idx) => { | |
obj[param] = match[idx] | |
return obj | |
}, {}) | |
// 3- Create handler chain and start processing request | |
let nextHandler | |
const handlerStack = route.handlers.slice().reverse() | |
const params = Object.values(request.params) | |
for(const handler of handlerStack){ | |
let lastNext = nextHandler | |
const next = () => { | |
handler(request, response, lastNext, ...params) | |
} | |
nextHandler = next | |
} | |
nextHandler() | |
handledRequest = true | |
break; | |
} | |
if(handledRequest){ | |
return | |
} | |
response.statusCode = 404; | |
response.end("Not Found !") | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment