Skip to content

Commit

Permalink
fix(context): calculate # of method params with default
Browse files Browse the repository at this point in the history
Fixes #1408
  • Loading branch information
raymondfeng committed Jun 11, 2018
1 parent 53457eb commit f5f5bde
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
9 changes: 6 additions & 3 deletions packages/context/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,16 @@ export function resolveInjectedArguments(
const extraArgs = nonInjectedArgs || [];

let argLength = DecoratorFactory.getNumberOfParameters(target, method);
if (argLength < injectedArgs.length) {

// Please note `injectedArgs` contains `undefined` for non-injected args
const numberOfInjected = injectedArgs.filter(i => i != null).length;
if (argLength < numberOfInjected + extraArgs.length) {
/**
* `Function.prototype.length` excludes the rest parameter and only includes
* parameters before the first one with a default value. For example,
* `hello(@inject('name') name: string)` gives 0 for argLength
* `hello(@inject('name') name: string = 'John')` gives 0 for argLength
*/
argLength = injectedArgs.length;
argLength = numberOfInjected + extraArgs.length;
}

let nonInjectedIndex = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ class InfoController {
debug(msg);
return msg;
}

greetWithDefault(
prefix: string = '***',
@inject('user') user: string,
): string {
const msg = `[${prefix}] Hello ${user}`;
debug(msg);
return msg;
}
}

const INFO_CONTROLLER = 'controllers.info';
Expand Down Expand Up @@ -60,6 +69,13 @@ describe('Context bindings - Injecting dependencies of method', () => {
expect(msg).to.eql('[INFO] Hello John');
});

it('injects prototype method args with non-injected ones with default', async () => {
const instance = await ctx.get(INFO_CONTROLLER);
// Invoke the `hello` method => Hello John
const msg = await invokeMethod(instance, 'greetWithDefault', ctx, ['INFO']);
expect(msg).to.eql('[INFO] Hello John');
});

it('injects static method args', async () => {
// Invoke the `sayHello` method => Hello John
const msg = await invokeMethod(InfoController, 'sayHello', ctx);
Expand Down

0 comments on commit f5f5bde

Please sign in to comment.