Closed3
TypeScript の MethodDecorator メモ
型定義
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
基本形
export function Decorator(): MethodDecorator {
return (
target: any,
methodName: string | symbol,
descriptor: TypedPropertyDescriptor<any>,
) => {
// デコレータを付与したメソッド
const originalMethod = descriptor.value;
console.log({ target, methodName, descriptor });
descriptor.value = function (...args: any[]) {
// 引数
console.log({ args });
const result = originalMethod.apply(this, args);
return result;
};
};
}
メソッドのラップをするときはメタデータや名前をコピーして置くのがいいっぽい?
ref: https://github.com/odavid/typeorm-transactional-cls-hooked/blob/c16e19f1727e3e55832848a4e135cc19fb7160fb/src/Transactional.ts
Reflect.getMetadataKeys(originalMethod).forEach(previousMetadataKey => {
const previousMetadata = Reflect.getMetadata(previousMetadataKey, originalMethod)
Reflect.defineMetadata(previousMetadataKey, previousMetadata, descriptor.value)
})
Object.defineProperty(descriptor.value, 'name', { value: originalMethod.name, writable: false })
このスクラップは3ヶ月前にクローズされました