Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/format.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

var mime = require('mime'),
path = require('path');

module.exports = function(app, defaultType) {
return function(env, callback) {
var extname, format, pathInfo;
pathInfo = env.pathInfo;
extname = path.extname(pathInfo);
format = extname ? mime.lookup(extname) : null;
env.format = format;

// Modify env.pathInfo for downstream apps
if (extname) {
env.pathInfo = pathInfo.replace(new RegExp("" + extname + "$"), "");
}


return app(env, function(status, headers, body) {
// Reset env.pathInfo for upstream apps.
env.pathInfo = pathInfo;

return callback(status, headers, body);
});
};
};
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ var propPaths = {
"contentType": "contenttype",
"directory": "directory",
"file": "file",
"format": "format",
"gzip": "gzip",
"jsonp": "jsonp",
"lint": "lint",
Expand Down
50 changes: 50 additions & 0 deletions test/format_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
var assert = require("assert"),
vows = require("vows"),
strata = require("./../lib"),
mock = strata.mock,
format = strata.format;

vows.describe("format").addBatch({
"A format middleware": {
topic: function () {
var app = function (env, callback) {
callback(200, {
"Content-Type": "text/plain",
"X-PathInfo": env.pathInfo,
"X-Format": env.format
}, "");
}

app = format(app);

return app;
},
"when /abc is requested": {
topic: function (app) {
mock.request("/abc", app, this.callback);
},
"should format properly": function (err, status, headers, body) {
assert.equal(headers["X-Format"], null);
assert.equal(headers["X-PathInfo"], "/abc");
}
},
"when /abc.json is requested": {
topic: function (app) {
mock.request("/abc.json", app, this.callback);
},
"should format properly": function (err, status, headers, body) {
assert.equal(headers["X-Format"], "application/json");
assert.equal(headers["X-PathInfo"], "/abc");
}
},
"when /abc.xml is requested": {
topic: function (app) {
mock.request("/abc.xml", app, this.callback);
},
"should format properly": function (err, status, headers, body) {
assert.equal(headers["X-Format"], "application/xml");
assert.equal(headers["X-PathInfo"], "/abc");
}
}
}
}).export(module);