Skip to content

Commit

Permalink
fix: should export createAsyncCtxStorageMiddleware function on applic…
Browse files Browse the repository at this point in the history
…ation (#1724)
  • Loading branch information
fengmk2 authored Dec 7, 2022
1 parent 382aa08 commit cb92bc9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
5 changes: 5 additions & 0 deletions __tests__/application/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,9 @@ describe('app', () => {
assert.deepStrictEqual(Koa.HttpError, CreateError.HttpError);
assert.throws(() => { throw new CreateError(500, 'test error'); }, Koa.HttpError);
});

it('should export createAsyncCtxStorageMiddleware function', () => {
const app = new Koa();
assert.strictEqual(typeof app.createAsyncCtxStorageMiddleware, 'function');
});
});
19 changes: 10 additions & 9 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ module.exports = class Application extends Emitter {
const { AsyncLocalStorage } = require('async_hooks');
assert(AsyncLocalStorage, 'Requires node 12.17.0 or higher to enable asyncLocalStorage');
this.ctxStorage = new AsyncLocalStorage();
this.use(createAsyncCtxStorage(this));
this.use(this.createAsyncCtxStorageMiddleware());
}
}

Expand Down Expand Up @@ -234,15 +234,16 @@ module.exports = class Application extends Emitter {
static get default() {
return Application;
}
};

function createAsyncCtxStorage(app) {
return async function asyncCtxStorage(ctx, next) {
await app.ctxStorage.run(ctx, async() => {
return await next();
});
};
}
createAsyncCtxStorageMiddleware() {
const app = this;
return async function asyncCtxStorage(ctx, next) {
await app.ctxStorage.run(ctx, async() => {
return await next();
});
};
}
};

/**
* Response helper.
Expand Down

0 comments on commit cb92bc9

Please sign in to comment.