[英]Safest way to guard against missing and undefined parameters?
我有一個函數,它從網絡調用中傳遞了一個參數,我想在這些參數為null
、丟失或以其他方式未定義時防范這些參數。 我可以簡單地將每個屬性默認為null
,然后檢查它們是否為null
作為我的守衛嗎? 或者有沒有更安全的方法?
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
}
});
如果truthiness
是您檢查參數的依據,您可以使用解構和真實評估來清理此代碼。 那看起來像這樣:
exports.pushNotify = functions.https.onCall((data, _context) => {
const { recipientUserId, senderUserId, senderName, messageText } = data;
const valid = recipientUserId && senderUserId && senderName && messageText;
if (!valid) {
// terminate
}
// proceed
});
考慮truthy
值的一種簡單方法是它不是null
、 undefined
、空字符串或 0。在此處查看所有真值/假值的表格: https ://dorey.github.io/JavaScript-Equality-Table / .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.