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
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ var Resource = module.exports = function Resource(name, actions, app) {
this.base = actions.base || '/';
if ('/' != this.base[this.base.length - 1]) this.base += '/';
this.format = actions.format;
this.formats = actions.formats;
if (this.formats && this.formats.length) {
this.format = this.formats[0];
}
this.id = actions.id || this.defaultId;
this.param = ':' + this.id;

Expand Down Expand Up @@ -126,7 +130,10 @@ Resource.prototype.map = function(method, path, fn){
var route = this.base + (this.name || '');
if (this.name && path) route += '/';
route += path;
route += '.:format?';
if (this.formats)
route += '.:format(' + this.formats.join('|') + ')?';
else
route += '.:format?';

// register the route so we may later remove it
(this.routes[method] = this.routes[method] || {})[route] = {
Expand Down
50 changes: 49 additions & 1 deletion test/resource.content-negotiation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,54 @@ module.exports = {
{ body: 'Unsupported format', status: 406 });
},

'test content-negotiation for known formats': function(){
var app = express.createServer();

app.resource('series', {
show: function(req, res){
res.send(req.format + ": " + req.params.series);
}
}, { formats: ['json', 'xml'] });

assert.response(app,
{ url: '/series/Dr.%20House.xml' },
{ body: 'xml: Dr. House'
, headers: { 'Content-Type': 'application/xml' }});

assert.response(app,
{ url: '/series/Dr.%20House.json' },
{ body: 'json: Dr. House'
, headers: { 'Content-Type': 'application/json' }});

assert.response(app,
{ url: '/series/Dr.%20House' },
{ body: 'json: Dr. House'
, headers: { 'Content-Type': 'application/json' }});

assert.response(app,
{ url: '/series/Dr.%20House.html' },
{ body: 'json: Dr. House.html'
, headers: { 'Content-Type': 'application/json' }});
},

'test content-negotiation with no format': function(){
var app = express.createServer();

app.resource('series', {
show: function(req, res){
res.send(req.params.series);
}
}, { formats: [] });

assert.response(app,
{ url: '/series/Dr.%20House' },
{ body: 'Dr. House' });

assert.response(app,
{ url: '/series/Dr.%20House.html' },
{ body: 'Dr. House.html' });
},

'test content-negotiation via format method without default': function(){
var app = express.createServer();

Expand Down Expand Up @@ -155,4 +203,4 @@ module.exports = {
{ url: '/users/1/pets.json' },
{ body: '["tobi","jane","loki"]' });
}
};
};