Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

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 McMahon authored June 28, 2010
9  lib/quickresponse.js
@@ -79,14 +79,13 @@ exports.update = function(res){
79 79
     res.atom = withType('application/atom+xml');
80 80
     res.rss = withType('application/rss+xml');
81 81
     res.javascript = withType('text/javascript');
82  
-    res.json = function(data){
83  
-        if(typeof data === 'object') data = JSON.stringify(data);
84  
-        res.headers({'Content-Type': 'application/json'});
85  
-        return data ? res.send(data): res;
86  
-    };
  82
+    res.json = withType('application/json');
87 83
 
88 84
     // respond with given data using current header and status code
89 85
     res.send = function(data){
  86
+        if(res._headers['Content-Type'] == 'application/json'){
  87
+            if(typeof data == 'object') data = JSON.stringify(data);
  88
+        }
90 89
         res.writeHead(res._status, res._headers);
91 90
         if(data) res.write(data);
92 91
         res.end();
19  test/test-response.js
@@ -126,7 +126,6 @@ exports.rss = mimeTypeTest('application/rss+xml', 'rss');
126 126
 exports.javascript = mimeTypeTest('text/javascript', 'javascript');
127 127
 exports.json = mimeTypeTest('application/json', 'json');
128 128
 
129  
-
130 129
 exports.send = function(test){
131 130
     test.expect(4);
132 131
     var res = quickresponse.update({
@@ -165,6 +164,24 @@ exports['send defaults'] = function(test){
165 164
     test.done();
166 165
 };
167 166
 
  167
+exports['send object literal as json'] = function(test){
  168
+    test.expect(6);
  169
+    var res = quickresponse.update({
  170
+        writeHead: function(code, headers){
  171
+            test.ok(true, 'writeHead called');
  172
+        },
  173
+        write: function(data){
  174
+            test.equals(data, '{"test":"object"}');
  175
+        },
  176
+        end: function(){
  177
+            test.ok(true, 'end called');
  178
+        }
  179
+    });
  180
+    res.json({test:'object'});
  181
+    res.json().ok({test:'object'});
  182
+    test.done();
  183
+};
  184
+
168 185
 exports.headers = function(test){
169 186
     test.expect(3);
170 187
     var res = quickresponse.update({});

0 notes on commit e853444

Please sign in to comment.
Something went wrong with that request. Please try again.