Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: runInAnonymousContextScope support req #5134

Merged
merged 2 commits into from
Jan 28, 2023
Merged
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.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -729,8 +729,9 @@ declare module 'egg' {
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
* @param {Request} req - if you want to mock request like querystring, you can pass an object to this function.
*/
runInAnonymousContextScope(scope: (ctx: Context) => Promise<void>): Promise<void>;
runInAnonymousContextScope<R>(scope: (ctx: Context) => Promise<R>, req?: Request): Promise<R>;

/**
* Get current execute ctx async local storage
Expand Down
9 changes: 5 additions & 4 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,12 +260,13 @@ class Application extends EggApplication {
* Run async function in the anonymous context scope
* @see Context#runInAnonymousContextScope
* @param {Function} scope - the first args is an anonymous ctx, scope should be async function
* @param {Request} [req] - if you want to mock request like querystring, you can pass an object to this function.
*/
async runInAnonymousContextScope(scope) {
const ctx = this.createAnonymousContext();
async runInAnonymousContextScope(scope, req) {
const ctx = this.createAnonymousContext(req);
if (!scope.name) scope._name = eggUtils.getCalleeFromStack(true);
await this.ctxStorage.run(ctx, async () => {
await scope(ctx);
return await this.ctxStorage.run(ctx, async () => {
return await scope(ctx);
});
}

Expand Down
2 changes: 1 addition & 1 deletion lib/egg.js
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ class EggApplication extends EggCore {
* Create an anonymous context, the context isn't request level, so the request is mocked.
* then you can use context level API like `ctx.service`
* @member {String} EggApplication#createAnonymousContext
* @param {Request} req - if you want to mock request like querystring, you can pass an object to this function.
* @param {Request} [req] - if you want to mock request like querystring, you can pass an object to this function.
* @return {Context} context
*/
createAnonymousContext(req) {
Expand Down