Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

stringify json data at point of sending, allows mime before status to…

… work with json object literals
  • Loading branch information...
commit e85344408f98c6db1a96ea1fe8b98efd723217fe 1 parent 1de1e01
@caolan authored
Showing with 22 additions and 6 deletions.
  1. +4 −5 lib/quickresponse.js
  2. +18 −1 test/test-response.js
View
9 lib/quickresponse.js
@@ -79,14 +79,13 @@ exports.update = function(res){
res.atom = withType('application/atom+xml');
res.rss = withType('application/rss+xml');
res.javascript = withType('text/javascript');
- res.json = function(data){
- if(typeof data === 'object') data = JSON.stringify(data);
- res.headers({'Content-Type': 'application/json'});
- return data ? res.send(data): res;
- };
+ res.json = withType('application/json');
// respond with given data using current header and status code
res.send = function(data){
+ if(res._headers['Content-Type'] == 'application/json'){
+ if(typeof data == 'object') data = JSON.stringify(data);
+ }
res.writeHead(res._status, res._headers);
if(data) res.write(data);
res.end();
View
19 test/test-response.js
@@ -126,7 +126,6 @@ exports.rss = mimeTypeTest('application/rss+xml', 'rss');
exports.javascript = mimeTypeTest('text/javascript', 'javascript');
exports.json = mimeTypeTest('application/json', 'json');
-
exports.send = function(test){
test.expect(4);
var res = quickresponse.update({
@@ -165,6 +164,24 @@ exports['send defaults'] = function(test){
test.done();
};
+exports['send object literal as json'] = function(test){
+ test.expect(6);
+ var res = quickresponse.update({
+ writeHead: function(code, headers){
+ test.ok(true, 'writeHead called');
+ },
+ write: function(data){
+ test.equals(data, '{"test":"object"}');
+ },
+ end: function(){
+ test.ok(true, 'end called');
+ }
+ });
+ res.json({test:'object'});
+ res.json().ok({test:'object'});
+ test.done();
+};
+
exports.headers = function(test){
test.expect(3);
var res = quickresponse.update({});
Please sign in to comment.
Something went wrong with that request. Please try again.