Skip to content

Commit

Permalink
Include async functions in origins promise detection
Browse files Browse the repository at this point in the history
  • Loading branch information
oshoemaker committed Dec 26, 2019
1 parent 71c4d00 commit 56ab6cf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ module.exports = function(options) {
let origin;
if (typeof options.origin === 'function') {
origin = options.origin(ctx);
if (origin instanceof Promise) origin = await origin;
const isAsync = origin.constructor.name === 'AsyncFunction';
if (origin instanceof Promise || isAsync) origin = await origin;
if (!origin) return await next();
} else {
origin = options.origin || requestOrigin;
Expand Down
29 changes: 29 additions & 0 deletions test/cors.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,35 @@ describe('cors.test.js', function() {
});
});

describe('options.origin=AsyncFunction', function() {
const asyncPromise = async () => {
return '*';
};

asyncPromise.constructor = {
name: 'AsyncFunction',
};

const app = new Koa();
app.use(cors({
origin: asyncPromise,
}));
app.use(function(ctx) {
ctx.body = { foo: 'bar' };
});

it('should allow ES2018 async functions', function(done) {
assert(asyncPromise.constructor.name === 'AsyncFunction');

request(app.listen())
.get('/')
.set('Origin', 'http://koajs.com')
.expect({ foo: 'bar' })
.expect('Access-Control-Allow-Origin', '*')
.expect(200, done);
});
});

describe('options.origin=async function', function() {
const app = new Koa();
app.use(cors({
Expand Down

0 comments on commit 56ab6cf

Please sign in to comment.