Created
October 25, 2012 16:27
-
-
Save creationix/3953821 to your computer and use it in GitHub Desktop.
architect http plugin for dynamic component building
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
module.exports = setup; | |
setup.consumes = ["http"]; | |
function setup(config, imports, register) { | |
imports.http.wrap(require('./middleware')(config)); | |
register(); | |
} |
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
module.exports = function (config) { | |
var Builder = require('component-builder'); | |
var cssUrl = config.cssUrl || "/build/build.css"; | |
var jsUrl = config.jsUrl || "/build/build.js"; | |
// Monkeypatch Builder to rewrite urls in css when concatting them. | |
var rootLength = config.componentPath.length; | |
if (config.componentPath[rootLength - 1] !== "/") rootLength++; | |
Builder.prototype.buildStyles = function(fn){ | |
this.buildType('styles', fn, function (builder, file, css) { | |
var prefix = "../" + builder.dir.substr(rootLength) + "/"; | |
var index = file.lastIndexOf("/"); | |
if (index >= 0) { | |
prefix += file.substr(0, index + 1); | |
} | |
return css.replace(/url\(['"][^\/][^'"]+['"]\)/g, function (css) { | |
css = "url(" + css[4] + prefix + css.substr(5); | |
return css; | |
}); | |
}); | |
}; | |
var queue; | |
function build(callback) { | |
if (queue) return queue.push(callback); | |
queue = [callback]; | |
var builder = new Builder(config.componentPath); | |
builder.build(function (err, res) { | |
var callbacks = queue; | |
queue = null; | |
callbacks.forEach(function (callback) { | |
callback(err, res); | |
}); | |
}); | |
} | |
return function (req, res, next) { | |
if (req.uri.pathname === cssUrl) { | |
build(function (err, result) { | |
if (err) return next(err); | |
res.setHeader("Content-Type", "text/css"); | |
res.setHeader("Content-Length", Buffer.byteLength(result.css)); | |
res.end(result.css); | |
}); | |
} | |
else if (req.uri.pathname === jsUrl) { | |
build(function (err, result) { | |
if (err) return next(err); | |
var js = result.require + result.js; | |
res.setHeader("Content-Type", "application/javascript"); | |
res.setHeader("Content-Length", Buffer.byteLength(js)); | |
res.end(js); | |
}); | |
} | |
else { | |
next(); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment