Skip to content

Commit

Permalink
fix: try to use custom function name first (#2161)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored and dead-horse committed Mar 5, 2018
1 parent 1a73720 commit f0edf96
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
3 changes: 2 additions & 1 deletion app/extend/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,9 @@ const proto = module.exports = {
runInBackground(scope) {
const ctx = this;
const start = Date.now();
// try to use custom function name first
/* istanbul ignore next */
const taskName = scope.name || scope._name || eggUtils.getCalleeFromStack(true);
const taskName = scope._name || scope.name || eggUtils.getCalleeFromStack(true);
// use app.toAsyncFunction to support both generator function and async function
ctx.app.toAsyncFunction(scope)(ctx)
.then(() => {
Expand Down
14 changes: 14 additions & 0 deletions test/app/extend/context.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,20 @@ describe('test/app/extend/context.test.js', () => {
);
});

it('should use custom task name first', async () => {
await app.httpRequest()
.get('/custom')
.expect(200)
.expect('hello');
await sleep(5000);
const logdir = app.config.logger.dir;
const log = fs.readFileSync(path.join(logdir, 'ctx-background-web.log'), 'utf8');
assert(/background run result file size: \d+/.test(log));
assert(
/\[egg:background] task:customTaskName success \(\d+ms\)/.test(fs.readFileSync(path.join(logdir, 'egg-web.log'), 'utf8'))
);
});

it('should run background task error', async () => {
mm.consoleLevel('NONE');
await app.httpRequest()
Expand Down
13 changes: 13 additions & 0 deletions test/fixtures/apps/ctx-background/app/controller/custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

const fs = require('mz/fs');

module.exports = async ctx => {
ctx.body = 'hello';
const fn = async function saveUserInfo(ctx) {
const buf = await fs.readFile(__filename);
ctx.logger.warn('background run result file size: %s', buf.length);
};
fn._name = 'customTaskName';
ctx.runInBackground(fn);
};
1 change: 1 addition & 0 deletions test/fixtures/apps/ctx-background/app/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

module.exports = app => {
app.get('/', app.controller.home);
app.get('/custom', app.controller.custom);
app.get('/app_background', app.controller.app);
app.get('/error', app.controller.error);
};

0 comments on commit f0edf96

Please sign in to comment.