Skip to content

Commit

Permalink
Koa fix for serveStatic
Browse files Browse the repository at this point in the history
  • Loading branch information
Karl Morrison committed Sep 22, 2016
1 parent 4ab2321 commit b6319a3
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions middleware/koa/serveStatic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
require('raptor-polyfill/string/startsWith');
require('raptor-polyfill/string/endsWith');

var lasso = require('../');
var send = require('send');
var extend = require('raptor-util/extend');

function notFound() {
this.error(404);
}

module.exports = function(options) {
options = options || {};

var myLasso = options.lasso || lasso.getDefaultLasso();
var config = myLasso.config;

var outputDir = config.outputDir;
var urlPrefix = config.urlPrefix;
var routePrefix = urlPrefix;
if (!routePrefix.endsWith('/')) {
routePrefix += '/';
}

if (!outputDir || !urlPrefix) {
return function(req, res, next) {
return next();
};
}

var sendOptions = {
fallthrough: false,
redirect: false,
index: false
};

if (options.sendOptions) {
extend(sendOptions, options.sendOptions);
}

sendOptions.root = outputDir;


return function(ctx, next) {
var req = ctx.request,
res = ctx.response;

var path = req.path;
if (!path.startsWith(routePrefix) || (req.method !== 'GET' && req.method !== 'HEAD')) {
return next();
}

var filePath = path.substring(routePrefix.length);

// create send stream
var stream = send(req, filePath, sendOptions);

// add directory handler
stream.on('directory', notFound);

// forward errors
stream.on('error', function error(err) {
res.statusCode = err.statusCode || 500;
res.end('Not found: ' + filePath);
});

// pipe
stream.pipe(res);
};
};

0 comments on commit b6319a3

Please sign in to comment.