我有這三個可呼叫函式,它們都在運行它們的主要邏輯之前進行身份驗證檢查。這似乎不是很干,我想知道是否有更聰明的方法來重用這個身份驗證邏輯?
exports.addComment = functions.https.onCall(async (data, { auth }) => {
if (auth) {
//logic to add comment
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
});
exports.deleteComment = functions.https.onCall(async (data, { auth }) => {
if (auth) {
//logic to delete comment
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
});
exports.updateComment = functions.https.onCall(async (data, { auth }) => {
if (auth) {
//logic to update comment
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
});
uj5u.com熱心網友回復:
我會在這里為您的場景使用裝飾器。
基本上裝飾器是一個函式,它接收一個函式并通過包裝它來擴展它的功能。
所以它看起來像這樣:
function authDecorator(functionWithLogic) {
let innerFunc = () => {
if (auth) {
return functionWithLogic()
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
return innerFunc
}
您還可以擴展它并根據需要將相關引數傳遞給它
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442615.html
上一篇:如何解構陣列/物件
