Last active
March 15, 2017 20:39
-
-
Save bolutife-lawrence/1414ccf0e94e3a9560bcacd4f4e0683a to your computer and use it in GitHub Desktop.
An HTTP-based `Router` in it's simplest form :)
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
'use strict'; | |
/** | |
* A very basic `RouterException` class. | |
**/ | |
export default class RouterException { | |
constructor (name, msg) { | |
this.name = name; | |
this.message = msg; | |
} | |
/** Prettify thrown error **/ | |
get errorString () { | |
return `Exception: ${this.name} ~ message: ${this.message}`; | |
} | |
} |
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
'use strict'; | |
import RouterException from "./routerException" | |
/** | |
* An HTTP-based `Router` in it's simplest form :) | |
**/ | |
class Router { | |
constructor () { | |
// Protect integrity of internally used router bindings. | |
Object.defineProperty(this, '_bindings', { | |
value: new Map(), | |
writable: true | |
}); | |
} | |
/** Public API for getting all registered/bound routes. **/ | |
get routes () { | |
return this._bindings.entries(); // List all routes on `this` router instance in insertion order. | |
} | |
/** Register/update route **/ | |
bind (url, method, action) { | |
switch (true) { | |
case Router.httpMethodsWhitelist.indexOf(method) === -1: // Check HTTP method validity. | |
throw new RouterException('InvalidHttpMethodException', 'Specified HTTP method is not recognized'); | |
case !(action instanceof Function): // Is specified action callable? | |
throw new RouterException('ActionNotCallableException', 'Could not execute specified route action'); | |
default: | |
// Finally, all checks passed, register/update route. | |
this._bindings.set(`${method}:${url}`, { action: action }); | |
} | |
} | |
/** Run registered action against the matched route **/ | |
runRequest (url, method) { | |
let requestedRoute = `${method}:${url}`; // Build up route URI. | |
if (!this._bindings.has(requestedRoute)) { // Check route existence. | |
throw new RouterException('ResourceNotFoundException', 'Requested resource is not registered'); | |
} | |
// Found `requestedRoute`? Execute associated action. | |
return this._bindings.get(requestedRoute).action.call(); | |
} | |
static get httpMethodsWhitelist () { | |
return ['POST', 'GET', 'PUT', 'DELETE', 'PATCH']; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment