我開發了一個裝飾器來將中間件添加到 AWS lambda,這里是源代碼。我的靈感來自 mediator 的源代碼(具體而言,此鏈接中的“RequestHandlerWrapperImpl”類)。所以我拿了 C# 代碼并試圖將它傳遞給 Typescript。簡化的代碼是這樣的。
// Used Types
type HandlerDelegate = () => Promise<APIGatewayProxyResult>;
type Handler = (event: APIGatewayProxyEvent) => Promise<APIGatewayProxyResult>
type Middleware = (event: APIGatewayProxyEvent, next: HandlerDelegate) => Promise<APIGatewayProxyResult>;
// Middlewares
const first = (event: APIGatewayProxyEvent, next: HandlerDelegate) =>{
console.log("first in")
const response = next();
console.log("first out")
return response;
};
const second = (event: APIGatewayProxyEvent, next: HandlerDelegate) =>{
console.log("second in")
const response = next();
console.log("second out")
return response;
};
// Executable logic
const read = forHandler(async () : Promise<APIGatewayProxyResult>
=> APIResponse.createSuccess(HttpStatusCode.OK, "handler"))
.addMiddleware(first)
.addMiddleware(second)
.finish;
// finish method
const finish = (event: APIGatewayProxyEvent) : Promise<APIGatewayProxyResult> => {
let result: HandlerDelegate = () => handler(event);
for (let i = 0; i < middlewares.length; i ) {
result = () => middlewares[i](event, result);
}
return result();
}
預期的日志是這樣的:
"first in"
"second in"
"handler"
"second in"
"first in"
但是,這是,直到溢位例外
"second in"
"second in"
"second in"
"second in"
"second in"
"second in"
"second in"
"second in"
有人可以解釋為什么會這樣嗎?我認為是因為在線
result = () => middlewares[i](event, result);
我完全替換了結果變數(在“兩側”)。因此,它不是遞回的,而是回圈的。另外,我怎樣才能讓它按預期作業?
uj5u.com熱心網友回復:
解決方案將完成功能修改為:
const finish = (event: APIGatewayProxyEvent) : Promise<APIGatewayProxyResult> => {
let result: HandlerDelegate = () => {
return handler(event);
};
for (let i = 0; i < middlewares.length; i ) {
let resultCallback = result;
result = () => {
return middlewares[i](event, resultCallback);
};
}
return result();
}
這樣,結果函式就不會被覆寫,我們讓管道作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470931.html
上一篇:在Java中遞回實作N選擇K
下一篇:如何檢查程式cout是否為空?