Permalink
Browse files

Port over Stack.mount and Stack.compose from luvit

  • Loading branch information...
creationix committed Nov 18, 2011
1 parent f49abf6 commit 80b0d7e5729d695ae9c2ba0e549c901a750478c4
Showing with 64 additions and 2 deletions.
  1. +1 −1 package.json
  2. +63 −1 stack.js
View
@@ -2,7 +2,7 @@
"name": "stack",
"description": "Stack is a minimal http module system for node.js",
"tags": ["connect", "middleware", "stack", "http"],
- "version": "0.0.3",
+ "version": "0.1.0",
"author": "Tim Caswell <tim@creationix.com>",
"repository": {
"type": "git",
View
@@ -1,3 +1,6 @@
+module.exports = Stack;
+var Url = require('url');
+
function Stack(/*layers*/) {
var error = Stack.errorHandler,
handle = error;
@@ -26,4 +29,63 @@ Stack.errorHandler = function error(req, res, err) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("Not Found\n");
};
-module.exports = Stack;
+
+function core(req, res, next) { next(); }
+
+// Build a composite stack made of several layers
+Stack.compose = function compose(/*layers*/) {
+ // Don't bother composing singletons
+ if (arguments.length == 1) { return arguments[0]; }
+
+ var stack = core;
+ Array.prototype.slice.call(arguments).reverse().forEach(function (layer) {
+
+ var child = stack;
+ stack = function (req, res, next) {
+ try {
+ layer(req, res, function (err) {
+ if (err) { return next(err); }
+ child(req, res, next);
+ });
+ } catch (err) {
+ next(err);
+ }
+ };
+
+ });
+
+ return stack;
+}
+
+// Mounts a substack app at a url subtree
+Stack.mount = function mount(mountpoint/*, stack*/) {
+
+ var stack = Stack.compose.apply(null, Array.prototype.slice.call(arguments, 1));
+
+ if (mountpoint.substr(mountpoint.length - 1) == "/") {
+ mountpoint = mountpoint.substr(0, mountpoint.length - 1);
+ }
+
+ var matchpoint = mountpoint + "/";
+
+ return function (req, res, next) {
+ var url = req.url;
+ var uri = req.uri;
+
+ if (url.substr(0, matchpoint.length) !== matchpoint) { return next(); }
+
+ // Modify the url
+ if (!req.realUrl) { req.realUrl = url; }
+
+ req.url = url.substr(mountpoint.length);
+ if (req.uri) { req.uri = Url.parse(req.url); }
+
+ stack(req, res, function (err) {
+ req.url = url;
+ req.uri = uri;
+ next(err)
+ });
+
+ };
+
+};

0 comments on commit 80b0d7e

Please sign in to comment.