Permalink
Browse files

add jsonp function

  • Loading branch information...
1 parent 8202fec commit 661cdc55d51851ecb44471cd56eb60a315ea4e9a @jifeng jifeng committed Nov 21, 2012
Showing with 51 additions and 2 deletions.
  1. +2 −1 Makefile
  2. +25 −0 lib/patch.js
  3. +2 −1 package.json
  4. +22 −0 test/patch.js
View
3 Makefile
@@ -2,6 +2,7 @@ TESTS = $(shell ls -S `find test -type f -name "*.js" -print`)
TIMEOUT = 1000
MOCHA_OPTS =
REPORTER = tap
+JSCOVERAGE = ./node_modules/jscover/bin/jscover
test:
@NODE_ENV=test node_modules/mocha/bin/mocha \
@@ -13,7 +14,7 @@ test-cov: lib-cov
lib-cov:
@rm -rf lib-cov
- @jscoverage lib lib-cov
+ @$(JSCOVERAGE) lib lib-cov
clean:
@rm -rf lib-cov
View
25 lib/patch.js
@@ -56,4 +56,29 @@ res.redirect = function (url, status) {
this.statusCode = status === 301 ? 301 : 302;
this.setHeader('Location', url);
this.end();
+};
+
+var APP_JS_CONTENT_TYPE = 'application/javascript';
+
+/**
+ * Jsonp
+ * @param {String} callback
+ * @param {Object} data, data of json
+ * @param {String} encoding, code default is 'utf-8'
+ * Examples:
+ *
+ * res.jsonp('callback', {"key": "value"});
+ * res.jsonp('callback', {"key": "value"}, 'utf8');
+ * @api public
+ */
+res.jsonp = function (callback, data, encoding) {
+ callback = callback || 'callback';
+ var body = JSON.stringify(data);
+ encoding = encoding || 'utf8';
+ body = callback + '(' + body + ')';
+ Buffer.byteLength(body, encoding);
+ this.setHeader('Content-Type', APP_JS_CONTENT_TYPE);
+ this.setHeader('Content-Length', Buffer.byteLength(body, encoding));
+ this.statusCode = 200;
+ this.end(body, encoding);
};
View
3 package.json
@@ -28,7 +28,8 @@
"should": "*",
"mocha": "*",
"supertest": "*",
- "pedding": "*"
+ "pedding": "*",
+ "jscover": "*"
},
"author": "fengmk2 <fengmk2@gmail.com>",
"license": "MIT"
View
22 test/patch.js
@@ -41,6 +41,12 @@ describe('patch.js', function () {
if (req.url === '/redirect/302') {
return res.redirect('/302', '302');
}
+ if (req.url === '/jsonp') {
+ return res.jsonp('callback', {key1: 'value1'});
+ }
+ if (req.url === '/jsonp/cb') {
+ return res.jsonp('cb', {key2: 'value2'});
+ }
});
it('should send(str)', function (done) {
@@ -92,4 +98,20 @@ describe('patch.js', function () {
.expect('Location', '/302', done);
});
+ it('should jsonp {"key1": "value1"}', function (done) {
+ request(app)
+ .get('/jsonp')
+ .expect(200)
+ .expect('Content-Type', 'application/javascript')
+ .expect(/{"key1":"value1"}/, done)
+ });
+
+ it('should jsonp {"key2": "value2"}', function (done) {
+ request(app)
+ .get('/jsonp/cb')
+ .expect(200)
+ .expect('Content-Type', 'application/javascript')
+ .expect(/{"key2":"value2"}/, done)
+ });
+
});

0 comments on commit 661cdc5

Please sign in to comment.