Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why we need this detect? When we call an async function, it will return a promise instance.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dead-horse , not always, the async function return a promise instance.

const p = new Promise(()=>{});
p instanceof Promise // true
const  a = async function () {}
a instanceof Promise // false
a.constructor.name === "AsyncFunction" // true 

chrome console
image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const  a = async function () {}
const result = a()
result instanceof Promise // true

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 = () => {
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