spirit-router
Version:
fast router for spirit
81 lines (68 loc) • 2.59 kB
JavaScript
;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var fs = require("fs");
var _require$node = require("spirit").node,
response = _require$node.response,
file_response = _require$node.file_response;
var Promise = require("bluebird");
var path = require("path");
var render = require("./render").render;
var resources = function resources() {
var mount_path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "";
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if ((typeof mount_path === "undefined" ? "undefined" : _typeof(mount_path)) === "object") {
opts = mount_path;
mount_path = "";
}
if (opts.root === undefined) opts.root = "public/";
if (opts.root !== "" && opts.root[opts.root.length - 1] !== "/") opts.root = opts.root + "/";
if (_typeof(opts.mime) !== "object") opts.mime = {};
return function (request, prefix) {
if (request.method !== "GET") {
return undefined;
}
var mount_pt = prefix + mount_path;
if (request.url.indexOf(mount_pt) !== 0) {
return undefined;
}
// remove the prefix + mount_path from the request url
// to get the correct file path
// additionally, remove any beginning "/"
var idx = mount_pt.length;
if (request.url[idx] === "/") idx += 1;
var fp = opts.root + request.url.slice(idx);
var opt_ext = opts.mime[path.extname(fp)];
return file_response(fp).then(function (resp) {
if (opt_ext) resp.type(opt_ext);
return resp;
}).catch(function (err) {
// the error doesn't matter too much,
// but catch to surpress and "pass" on this route
return undefined;
});
};
};
/**
* Convienance route for always returning a 404 response
*
* @param {string} method - optional, match only for method, otherwise matches all methods
* @param {*} body - valid response body
* @returns {function} function that always returns a 404 of the `body` if `method` matches
*/
var not_found = function not_found(method, body) {
if (!body) {
body = method;
method = "*";
} else {
method = method.toUpperCase();
}
return function (request) {
if (method === "*" || request.method === method) {
return render(request, body).status_(404);
}
};
};
module.exports = {
resources: resources,
not_found: not_found
};