From 9062775c58440b365c34f31fc6c752b1124656eb Mon Sep 17 00:00:00 2001 From: Alex MacCaw Date: Sun, 12 Feb 2012 11:16:53 -0800 Subject: [PATCH] add format middleware --- lib/format.js | 26 +++++++++++++++++++++++ lib/index.js | 1 + test/format_test.js | 50 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 lib/format.js create mode 100644 test/format_test.js diff --git a/lib/format.js b/lib/format.js new file mode 100644 index 0000000..920860c --- /dev/null +++ b/lib/format.js @@ -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); + }); + }; +}; \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index 4b7f13c..71e3fc2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -326,6 +326,7 @@ var propPaths = { "contentType": "contenttype", "directory": "directory", "file": "file", + "format": "format", "gzip": "gzip", "jsonp": "jsonp", "lint": "lint", diff --git a/test/format_test.js b/test/format_test.js new file mode 100644 index 0000000..59bddf1 --- /dev/null +++ b/test/format_test.js @@ -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); \ No newline at end of file