I have a function that is passed an argument from a network call and I want to guard against these arguments when they are null, missing, or otherwise undefined. Can I simply default each property to null and then check against them being null as my guard? Or is there a safer way?
exports.pushNotify = functions.https.onCall((data, _context) => {
const recipientUserId = data.recipientUserId || null;
const senderUserId = data.senderUserId || null;
const senderName = data.senderName || null;
const messageText = data.messageText || null;
if (recipientUserId != null && senderUserId != null && senderName != null && messageText != null) {
// proceed
} else {
// terminate
}
});
If truthiness is what you're checking against for your arguments, you can clean this code up with destructuring and truthy evaluation. That would look like this:
exports.pushNotify = functions.https.onCall((data, _context) => {
const { recipientUserId, senderUserId, senderName, messageText } = data;
const valid = recipientUserId && senderUserId && senderName && messageText;
if (!valid) {
// terminate
}
// proceed
});
A simple way to think about a truthy value is that it is not null, undefined, empty string, or 0. See a table of all truthy/falsy values here: https://dorey.github.io/JavaScript-Equality-Table/.