Skip to content

Commit

Permalink
callbackFn类型校验
Browse files Browse the repository at this point in the history
  • Loading branch information
keenwon committed Sep 7, 2016
1 parent 580b3a8 commit 458f6ee
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
17 changes: 12 additions & 5 deletions lib/jsonp.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,20 @@
const debug = require('debug')('koa-jsonp');
const assert = require('assert');

const defaultOptions = {
callbackFn: 'callback'
};
const defaultcallbackFn = 'callback';

module.exports = jsonp;

function jsonp(app, options = {}) {
assert(app && app.constructor.name === 'Application', 'app is must be an instance of koa');

const opts = Object.assign({}, defaultOptions, options);
const callbackFn = opts.callbackFn;
var callbackFn;
if (options.callbackFn) {
assert(isString(options.callbackFn), 'callbackFn must be string');
callbackFn = options.callbackFn;
} else {
callbackFn = defaultcallbackFn;
}

app.context.jsonp = function (data) {
var callback = this.query[callbackFn];
Expand All @@ -25,4 +28,8 @@ function jsonp(app, options = {}) {
this.type = 'application/json';
this.body = `${callback}(${JSON.stringify(data)})`;
}
}

function isString(str) {
return Object.prototype.toString.call(str) === '[object String]';
}
10 changes: 10 additions & 0 deletions test/jsonp.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ describe('koa-json测试', function () {
.equal('Not Found');
});

it('callback测试:callback类型错误', function () {
(function () {
const app = koa();

jsonp(app, {
callbackFn: true
});
}).should.throw('callbackFn must be string');
});

it('callback测试:自定义callback', function () {
const app = koa();

Expand Down

0 comments on commit 458f6ee

Please sign in to comment.