Skip to content

Instantly share code, notes, and snippets.

@realistschuckle
Created February 23, 2014 03:41
Show Gist options
  • Save realistschuckle/9166528 to your computer and use it in GitHub Desktop.
Save realistschuckle/9166528 to your computer and use it in GitHub Desktop.
An asset middleware component for Yahoo! Mojito that uses CouchDB attachments
/*jslint anon:true, sloppy:true, nomen:true, white:true, stupid:true*/
var http = require('http')
, path = require('path')
, url = require('url')
, ycb = require('ycb')
, fs = require('fs')
;
var uripattern = /^\/static\/([a-zA-Z0-9\-\._~]+)\/([a-zA-Z0-9\-\._~]+)\/([a-zA-Z0-9\-\._~]+)/
, configPath = path.join(__dirname, '../', 'application.json')
, appConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'))
, appConfig = new ycb.Ycb(appConfig, {})
;
function getBody(asseturi, res, next) {
http.get(asseturi, function(dbfile) {
var headers = dbfile.headers
;
if (dbfile.statusCode !== 200) {
return next();
}
Object.keys(headers).forEach(function(key) {
res.setHeader(key, headers[key]);
});
dbfile.pipe(res);
}).on('error', function(e) {
next(e);
});
}
module.exports = function(req, res, next) {
var matches = req.url.match(uripattern)
, noneMatch = req.headers['if-none-match']
, config = appConfig.read(req.app.store.getStaticContext())
, appName = config.staticHandling.appName
, dburi = config[appName].database.server
, chapter
, id
, attachment
, headopts
, asseturipath
, asseturi
;
if(!matches || matches.length === 0) {
return next();
}
chapter = matches[1];
id = matches[2];
attachment = matches[3];
asseturipath = path.join(chapter, id, attachment);
asseturi = url.resolve(dburi, asseturipath);
if (noneMatch) {
headopts = url.parse(asseturi);
headopts.method = 'HEAD';
http.request(headopts)
.on('response', function(headRes) {
var headers = headRes.headers
;
headRes.resume();
if (headRes.headers.etag === noneMatch) {
headers['content-length'] = 0;
res.writeHead(304, headers);
res.end();
} else {
getBody(asseturi, res, next);
}
}).on('error', function(e) {
next(e);
}).end();
} else {
getBody(asseturi, res, next);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment