以下是使用靜態類和方法decorators的示例。
foo.ts
// method decorator
function middleware() {
return function(target: any, propertyKey: string) {
// exec middleware
console.log('middleware')
}
}
export namespace Foo {
export class Bar {
constructor() {
throw new Error('Instantiating is not allowed');
}
@middleware()
static baz() {
console.log('after middleware');
}
}
}
這仍然會保持你的命名空間約定。
index.ts
import { Foo } from './foo';
Foo.Bar.baz();
該中間件將觸發方法baz
被調用之前。但是,如果你的中間件是async
,你需要裝飾的方法,以等待要完成的中間件,可以中間件更改爲類似如下:
function middleware() {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
let fn = descriptor.value;
return {
configurable: true,
get() {
return() => {
console.log('middleware');
wait(1000).then(() => wait(1000)).then(() => fn.call());
}
}
}
};
}
function wait(millis: number) {
console.log(`wait ${millis}ms`);
return new Promise<void>(resolve => {
setTimeout(resolve, millis);
});
}
或者,如果你喜歡async
和await
,你可以改變get
函數返回Promise<void>
類型,而不是一個功能:
get() {
return async() => {
console.log('middleware')
await wait(1000);
await wait(1000);
fn.call();
}
}
你能在這個問題 – marvel308
''命名空間Foo.Bar { applyMiddleWare(下){ 如果(啓用)NE提供一個例子XT(); } 導出功能觸發(){// 因此,一些 }} '' 因此,當觸發方法被調用時,我希望有一箇中間件功能首先執行。中間件將決定是否執行觸發器功能。 –
這個問題很快就會被解決,除非你用更好的解釋和代碼編輯它。 –