I have these three callable functions that all do an auth check before running their main logic. This doesn't seem very DRY and I would like to know if there was a more clever way to reuse this auth logic?
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"
);
}
});
CodePudding user response:
i would use here decorator for your scenario.
basically decorator is a function which receives a function and extend it's functionality by wrapping it.
so it would look something like that:
function authDecorator(functionWithLogic) {
let innerFunc = () => {
if (auth) {
return functionWithLogic()
} else {
throw new functions.https.HttpsError(
"failed-precondition",
"You must be authenticated"
);
}
return innerFunc
}
you can also extend it and pass relevant params to it as needed