我有这三个可调用函数,它们都在运行主逻辑之前进行身份验证检查。这似乎不是很枯燥,我想知道是否有更聪明的方法来重用这个身份验证逻辑?
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"
);
}
});
我会在这里为您的场景使用装饰器。
基本上decorator是一个接收函数并通过包装来扩展其功能的函数
所以它看起来像这样:
function authDecorator(functionWithLogic) {
let innerFunc = () => {
if (auth) {
return functionWithLogic()
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
return innerFunc
}
您还可以根据需要扩展它并将相关参数传递给它