metadata-hooks
v1.1.0
Published
Functions for use metadata from class decorator in method decorator
Downloads
23
Readme
Description
Hooks for use class metadata in method or property decorator
Installation
npm install --save metadata-hooks
Usage
Create class decorator for defining scope in class metadata
// scope.decorator.ts
import { setClassMetadata } from 'metadata-hooks';
function Scope(scope: string): ClassDecorator {
return setClassMetadata('scope', scope);
}
export { Scope };
Create method decorator using class metadata for saving method names unique per scope
// method.decorator.ts
import { useClassMetadata } from 'metadata-hooks';
const usedMethods = new Map <string, Set <string>> ();
function Method(): MethodDecorator {
return useClassMetadata('scope', (scope: string) => {
const scopeMethods = usedMethods.get(scope) ?? new Set();
if (!usedMethods.has(scope)) {
usedMethods.set(scope, scopeMethods);
}
return (prototype: Prototype, methodName: string) => {
if (scopeMethods.has(methodName)) {
throw new Error(`Method '${methodName}' is already used in scope '${scope}'`);
}
Reflect.defineMetadata('methodName', `${scope}:${methodName}`, prototype, methodName);
scopeMethods.add(methodName);
};
});
}
export { Method };
Use decorators @Scope()
and @Method()
// main.ts
import { Scope } from './scope.decorator';
import { Method } from './method.decorator';
@Scope('company')
class UserController {
@Method() // <-- Ok
public createCompany(name: string): Company {
// ...
}
@Method() // <-- Ok
public getCompanies(): Company[] {
// ...
}
}
@Scope('company')
class AdminController {
@Method() // <-- Error
// Method 'getCompanies' is already used in scope 'company'
public getCompanies(): Company[] {
// ...
}
}
License
MIT