diff --git a/index.js b/index.js index 9452af8..85395a3 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/test/cors.test.js b/test/cors.test.js index 2bd05d4..dbc70f3 100644 --- a/test/cors.test.js +++ b/test/cors.test.js @@ -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({