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: Add decorator factories and refactor into @loopback/metadata #775

Merged
merged 11 commits into from
Dec 15, 2017
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ packages/*/api-docs
packages/cli/generators/*/templates
package.json
packages/*/package.json
*.md
23 changes: 11 additions & 12 deletions packages/authentication/src/decorators/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {Reflector, Constructor} from '@loopback/context';
import {
MetadataInspector,
Constructor,
MethodDecoratorFactory,
} from '@loopback/context';
import {AuthenticationBindings} from '../keys';

/**
Expand All @@ -21,18 +25,13 @@ export interface AuthenticationMetadata {
* @param options Additional options to configure the authentication.
*/
export function authenticate(strategyName: string, options?: Object) {
return function(controllerClass: Object, methodName: string) {
const metadataObj: AuthenticationMetadata = {
return MethodDecoratorFactory.createDecorator<AuthenticationMetadata>(
AuthenticationBindings.METADATA,
{
strategy: strategyName,
options: options || {},
};
Reflector.defineMetadata(
AuthenticationBindings.METADATA,
metadataObj,
controllerClass,
methodName,
);
};
},
);
}

/**
Expand All @@ -45,7 +44,7 @@ export function getAuthenticateMetadata(
controllerClass: Constructor<{}>,
methodName: string,
): AuthenticationMetadata | undefined {
return Reflector.getMetadata(
return MetadataInspector.getMethodMetadata<AuthenticationMetadata>(
AuthenticationBindings.METADATA,
controllerClass.prototype,
methodName,
Expand Down
2 changes: 1 addition & 1 deletion packages/context/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"author": "IBM",
"license": "MIT",
"dependencies": {
"reflect-metadata": "^0.1.10"
"@loopback/metadata": "^4.0.0-alpha.1"
},
"devDependencies": {
"@loopback/build": "^4.0.0-alpha.7",
Expand Down
4 changes: 2 additions & 2 deletions packages/context/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export {
export {Context} from './context';
export {Constructor} from './resolver';
export {inject, Setter, Getter} from './inject';
export {NamespacedReflect} from './reflect';
export {Provider} from './provider';
export {isPromise} from './is-promise';

Expand All @@ -25,4 +24,5 @@ export {
describeInjectedProperties,
Injection,
} from './inject';
export {Reflector} from './reflect';

export * from '@loopback/metadata';
91 changes: 48 additions & 43 deletions packages/context/src/inject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

import {Reflector} from './reflect';
import {
MetadataInspector,
ParameterDecoratorFactory,
PropertyDecoratorFactory,
MetadataMap,
} from '@loopback/metadata';
import {BoundValue, ValueOrPromise} from './binding';
import {Context} from './context';

Expand Down Expand Up @@ -60,42 +65,51 @@ export function inject(
return function markParameterOrPropertyAsInjected(
// tslint:disable-next-line:no-any
target: any,
propertyKey?: string | symbol,
propertyDescriptorOrParameterIndex?:
propertyKey: string | symbol,
methodDescriptorOrParameterIndex?:
| TypedPropertyDescriptor<BoundValue>
| number,
) {
if (typeof propertyDescriptorOrParameterIndex === 'number') {
if (typeof methodDescriptorOrParameterIndex === 'number') {
// The decorator is applied to a method parameter
// Please note propertyKey is `undefined` for constructor
const injectedArgs: Injection[] =
Reflector.getOwnMetadata(PARAMETERS_KEY, target, propertyKey!) || [];
injectedArgs[propertyDescriptorOrParameterIndex] = {
bindingKey,
metadata,
resolve,
};
Reflector.defineMetadata(
const paramDecorator: ParameterDecorator = ParameterDecoratorFactory.createDecorator(
PARAMETERS_KEY,
injectedArgs,
target,
propertyKey!,
{
bindingKey,
metadata,
resolve,
},
);
paramDecorator(target, propertyKey!, methodDescriptorOrParameterIndex);
} else if (propertyKey) {
// Property or method
if (typeof Object.getPrototypeOf(target) === 'function') {
const prop = target.name + '.' + propertyKey.toString();
throw new Error(
'@inject is not supported for a static property: ' + prop,
);
}
// The decorator is applied to a property
const injections: {[p: string]: Injection} =
Reflector.getOwnMetadata(PROPERTIES_KEY, target) || {};
injections[propertyKey] = {bindingKey, metadata, resolve};
Reflector.defineMetadata(PROPERTIES_KEY, injections, target);
if (methodDescriptorOrParameterIndex) {
// Method
throw new Error(
'@inject cannot be used on a method: ' + propertyKey.toString(),
);
}
const propDecorator: PropertyDecorator = PropertyDecoratorFactory.createDecorator(
PROPERTIES_KEY,
{
bindingKey,
metadata,
resolve,
},
);
propDecorator(target, propertyKey!);
} else {
// It won't happen here as `@inject` is not compatible with ClassDecorator
/* istanbul ignore next */
throw new Error(
'@inject can only be used on properties or method parameters.',
'@inject can only be used on a property or a method parameter',
);
}
};
Expand Down Expand Up @@ -176,11 +190,13 @@ export function describeInjectedArguments(
target: any,
method?: string | symbol,
): Injection[] {
if (method) {
return Reflector.getMetadata(PARAMETERS_KEY, target, method) || [];
} else {
return Reflector.getMetadata(PARAMETERS_KEY, target) || [];
}
method = method || '';
const meta = MetadataInspector.getAllParameterMetadata<Injection>(
PARAMETERS_KEY,
target,
method,
);
return meta || [];
}

/**
Expand All @@ -191,22 +207,11 @@ export function describeInjectedArguments(
export function describeInjectedProperties(
// tslint:disable-next-line:no-any
target: any,
): {[p: string]: Injection} {
const metadata: {[name: string]: Injection} = {};
let obj = target;
while (true) {
const m = Reflector.getOwnMetadata(PROPERTIES_KEY, obj);
if (m) {
// Adding non-existent properties
for (const p in m) {
if (!(p in metadata)) {
metadata[p] = m[p];
}
}
}
// Recurse into the prototype chain
obj = Object.getPrototypeOf(obj);
if (!obj) break;
}
): MetadataMap<Injection> {
const metadata =
MetadataInspector.getAllPropertyMetadata<Injection>(
PROPERTIES_KEY,
target,
) || {};
return metadata;
}
10 changes: 10 additions & 0 deletions packages/context/test/unit/inject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ describe('property injection', () => {
}).to.throw(/@inject is not supported for a static property/);
});

it('cannot decorate a method', () => {
expect(() => {
// tslint:disable-next-line:no-unused-variable
class TestClass {
@inject('bar')
foo() {}
}
}).to.throw(/@inject cannot be used on a method/);
});

it('supports inheritance without overriding property', () => {
class TestClass {
@inject('foo') foo: string;
Expand Down
3 changes: 3 additions & 0 deletions packages/metadata/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.tgz
dist*
package
1 change: 1 addition & 0 deletions packages/metadata/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
25 changes: 25 additions & 0 deletions packages/metadata/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright (c) IBM Corp. 2017. All Rights Reserved.
Node module: @loopback/metadata
This project is licensed under the MIT License, full text below.

--------

MIT license

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Loading