1.4.0A standalone HTTP router that's based on the principle of middleware. Based on rill (see the npm package bearing the name), but stripped down and simplified.
(Boolean
= false)
Whether to be verbose and log a bunch of things to the console. Useful for debugging.
Whether to activate verbose mode. Useful for debugging the router.
Shortcut function for attaching an action to any request method. Full function: on
(Function)
The function to execute when this route is matches.gets passed 2 parameters: context (or type RequestContext) and next (a function). context contains the request / response objects, and next() should be called if the action is middleware.
Shortcut function for attaching an action to head requests. Full function: on
(Function)
The function to execute.
router.head("/location/:name/status", (context, _next) => {
context.send.plain(200, `Coming in from ${context.params.type} - status ok!`);
});
Shortcut function for attaching an action to get requests. Full function: on
(Function)
The function to execute.
router.get("/tree/:type", (context, _next) => {
context.send.plain(200, `Hello, I am a ${context.params.type}`);
});
Shortcut function for attaching an action to post requests. Full function: on
(Function)
The function to execute.
router.post("/loaction/:name/update", (context, _next) => {
context.send.plain(501, `Hello from ${context.params.name}! I don't yet support updating my firmware.\nYou asked me to update to version ${context.post_data.version}.`);
// See https://github.com/sbrl/powahroot/blob/master/examples/parse_post_data.mjs for an example of parsing post data with middleware that works with the above (context.post_data is not created automatically by powahroot)
});
Shortcut function for attaching an action to options requests. Full function: on
(Function)
The function to execute.
router.options("/location/:name/status", (context, _next) => {
context.send.plain(200, `I support these actions:\n - GET: Get my status\n - POST: Set my status\n - OPTIONS: Show this message`);;
});
Execute the specified action for requests matching the given parameters. TODO: Consider merging with on_all and refactoring to take an object literal which we can destructure instead
(array)
The HTTP methods to run the action for. Include '*' to specify all methods.
((string | regex))
The specification of the paths that this action should match against. May be a regular expression.
(Function)
The action to execute. Will be passed the parameters
context
(RouterContext) and
next
(Function).
router.on(["get"], "/garden/:vegetable", (context) => {
context.send(201, `Planted ${context.params.vegetable}`);
});
Adds a route that matches against every request. Usually useful for middleware (e.g. error handlers, request loggers, authentication handlers, etc.).
(Function)
The function to execute.
router.on_all((context) => {
context.send.plain(200, "Hello, world!");
});
Runs the specified action for requests if the provided testing function returns true.
Handles the specified request. Don't forget to await the Promise!
(http.ClientRequest)
The request to handle.
(http.ServerResponse)
The response object to use to send the response.
Promise:
A Promise that resolves when handling is complete.
const server = http.createServer(async (request, response) => {
await router.handle(request, response);
});
server.listen(3500, "127.0.0.1", () => console.log("Listening on http://127.0.0.1:3500/"));
Iterates over all the generated middleware.
Generator:
A generator that returns each successive piece of middleware in turn.
Contains context information about a single request / response pair.
(any)
(any)
Returns the parsed querystring from the request url, or an empty object if no query string was found.
NOTE FROM THE NODE.JS DOCS: The object returned by the querystring.parse() method [used in this getter] does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.
Object:
The parsed query string as an object, or an empty object.
The Node.JS request object
Type: http.ClientRequest
The Node.JS response object
Type: http.ServerResponse
The parsed request URL
The built-in Node.js url module (and NOT the browser-like URL class) is used for parsing URLs.
This is because the WHATWG URL API does not support relative URLS: https://github.com/nodejs/node/issues/12682
See the querystring getter for a portable way to grab the parsed query string.
Type: URL
The environment object. State variables that need to be attached to a specific request can go in here.
Type: RequestEnvironment
Helper methods for quickly sending responses to clients.
(http.ServerResponse)
The response object to use when sending requests.
Sends a HTML response, rendering a NightInk template. Don't forget to await this!
(number)
The status code to return.
(string)
The path to the filename containing the template to render.
(Object)
The data to use whilst rendering the template.
Promise:
Sends a given string as a HTML response
void:
Sends a plain text response.
Sends a redirect.
Holds request environment and state variables.
(any)
The user's name. Guaranteed to be specified - if only as "anonymous".
Type: String
Converts a path specification into a regular expression. Originally from the server-side sibling of this (client-side) router.
(string)
The path specification to convert.
(Boolean
= false)
Optional. Whether to be verbose and log some stuff to the console. Default: false
RegExp:
The resulting regular expression
Client-side request router. You should use this in a browser. If you're not in a browser, you probably want ServerRouter instead.
Extends EventEmitter
(object)
The options object to use when creating the router.
(Boolean)
: Whether to be verbose and log debugging information to the console.
(Boolean)
: Whether to listen to the browser's
pushstate
event and automatically navigate on recieving it.
Whether we should handle popstate events or not. @type {Boolean}
Adds a route to the router.
(Function)
The callback to execute when the route is matched.
router.add_page("/add/vegetable/:name/:weight", (params) => console.log(`We added a ${params.name} with a weight of ${params.weight}g.`));
Navigate to the current URL's hash value - i.e. the bit after the '#' symbol in the URL.
router.navigate_current_hash();
Namespaced logging manager.
Logs to stdout.
(any)
Generates various VT100 ANSI escape sequences.
Ported from C#.
This is a powahroot-internal class that @sbrl copies across various projects, but can be used outside. There is no guarantee of stability, though this API has been pretty stable.
Author: Starbeamrainbowlabs GitHub: @sbrl | Twitter: @SBRLabs | Reddit: u/Starbeamrainbowlabs **** Changelog ***** 27th March 2019:
Simple logging class
This is a powahroot-internal class, but can be used outside. There is no guarantee of stability, though this API has been pretty stable.
Middleware for logging requests to stdout.
(RouterContext)
The router context to operate on.
(Function)
The next() function that is provided by powahroot.
void:
import { ServerRouter, middleware_log_requests } from 'powahroot/Server.mjs';
// ...
const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");
// Note that ordering matters here! If they were called the other way around then the `.get()` call would be called first before the logger has been registered!
// Note also that you would want to register the error handler BEFORE the logger.... because in the unlikely event the logger crashes it would otherwise bring down the entire server!
router.on_all(middleware_log_requests);
router.get(`/some_other_route`, another_handler);
Handles errors thrown by handlers further down the chain.
(RequestContext)
The RequestContext object.
(Function)
The function to call to invoke the next middleware item
import { ServerRouter, middleware_catch_errors } from 'powahroot/Server.mjs';
// ...
const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");
// Note that ordering matters here! If they were called the other way around then the `.get()` call would be called first before the error handler has been registered!
router.on_all(middleware_catch_errors);
router.get(`/some_other_route`, another_handler);
Middleware that reads the request body from the client, parses it as JSON, and attaches it to context.env.body.
Does nothing if the client doesn't set the correct content-type of application/json.
IMPORTANT: Unlike the other builtin middlewares, this is a function that returns the REAL middleware function! This is because we need some way to pass options to it elegantly without requiring function binding etc which looks bad.
(number
= 2*1024*1024)
The maximum length of the client body to accept before returning a HTTP error 413 content too large. Defaults to 2MB,
function:
The real middleware function.
import { ServerRouter, middleware_parse_json } from 'powahroot/Server.mjs';
// ...
const router = new ServerRouter((typeof process.env.DEBUG_ROUTES) === "string");
// Note that ordering matters here! If they were called the other way around then the `.post()` call would be called first before the JSON parser middleware has been registered!
// Note also that you would want to register the error handler BEFORE the JSON parser.... because in the event the JSON parser crashes it would otherwise bring down the entire server!
router.on_all(middleware_parse_json(100)); // Allow a max of 100 BYTES of JSON
router.post(`/some_other_route`, another_handler);