Skip to content

Commit

Permalink
feat: allow ctx.router setter (#3460)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored and dead-horse committed Feb 14, 2019
1 parent ae5f56f commit 0b67c85
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
14 changes: 12 additions & 2 deletions app/extend/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const LOCALS_LIST = Symbol('Context#localsList');
const COOKIES = Symbol('Context#cookies');
const CONTEXT_LOGGERS = Symbol('Context#logger');
const CONTEXT_HTTPCLIENT = Symbol('Context#httpclient');

const CONTEXT_ROUTER = Symbol('Context#router');

const proto = module.exports = {

Expand Down Expand Up @@ -59,9 +59,19 @@ const proto = module.exports = {
* ```
*/
get router() {
return this.app.router;
if (!this[CONTEXT_ROUTER]) {
this[CONTEXT_ROUTER] = this.app.router;
}
return this[CONTEXT_ROUTER];
},

/**
* Set router to Context, only use on EggRouter
* @param {EggRouter} val router instance
*/
set router(val) {
this[CONTEXT_ROUTER] = val;
},

/**
* Get helper instance from {@link Application#Helper}
Expand Down
2 changes: 1 addition & 1 deletion test/app/extend/context.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ describe('test/app/extend/context.test.js', () => {
});
after(() => app.close());

describe('ctx.router', () => {
describe('ctx.router getter and settter', () => {
it('should work', () => {
return app.httpRequest()
.get('/')
Expand Down
13 changes: 8 additions & 5 deletions test/fixtures/apps/context-config-app/app/controller/home.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
'use strict';

exports.index = function* () {
this.body = {
path: this.router.pathFor('home'),
foo: this.foo,
bar: this.bar()
exports.index = async ctx => {
const router = ctx.router;
// set router ok too
ctx.router = router;
ctx.body = {
path: ctx.router.pathFor('home'),
foo: ctx.foo,
bar: ctx.bar()
};
};

0 comments on commit 0b67c85

Please sign in to comment.