Skip to content

Commit

Permalink
fix(context): check constructor/method override for @Inject
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondfeng committed Aug 14, 2018
1 parent 5a6bed8 commit 8c0bdb6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions packages/context/src/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
PropertyDecoratorFactory,
MetadataMap,
MetadataAccessor,
InspectionOptions,
} from '@loopback/metadata';
import {BoundValue, ValueOrPromise, resolveList} from './value-promise';
import {Context} from './context';
Expand Down Expand Up @@ -299,10 +300,23 @@ export function describeInjectedArguments(
method?: string,
): Readonly<Injection>[] {
method = method || '';
const options: InspectionOptions = {};
if (method === '') {
// A hacky way to check if an explicit constructor exists
// See https://github.com/strongloop/loopback-next/issues/1565
if (target.toString().match(/\s+constructor\s*\([^\)]*\)\s+\{/m)) {
options.ownMetadataOnly = true;
}
} else if (target.hasOwnProperty(method)) {
// The method exists in the target, no injections on the super method
// should be honored
options.ownMetadataOnly = true;
}
const meta = MetadataInspector.getAllParameterMetadata<Readonly<Injection>>(
PARAMETERS_KEY,
target,
method,
options,
);
return meta || [];
}
Expand Down
14 changes: 14 additions & 0 deletions packages/context/test/unit/inject.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ describe('function argument injection', () => {
const meta = describeInjectedArguments(SubTestClass);
expect(meta.map(m => m.bindingKey)).to.deepEqual(['bar']);
});

it('supports inheritance with overriding constructor - no args', () => {
class TestClass {
constructor(@inject('foo') foo: string) {}
}

class SubTestClass extends TestClass {
constructor() {
super('foo');
}
}
const meta = describeInjectedArguments(SubTestClass);
expect(meta.map(m => m.bindingKey)).to.deepEqual([]);
});
});

describe('property injection', () => {
Expand Down

0 comments on commit 8c0bdb6

Please sign in to comment.