[英]What is the proper way to use only variables that contain data in Node JS?
我一直在 Node JS 和 Swift 中對此進行研究。 我的 iOS 應用程序中有一個“表格”,它為我提供了以下 3 個選項:
可能存在用戶僅更新默認卡、僅更新日期之一或兩者而不更新默認卡的情況。 兩個日期等,任何可能的更新方案。
我的問題是,我怎樣才能讓這個 function 接受空白或 null 輸入? 我知道我可以將 CONST 變量設置為 null 開始,但是如何防止將其作為空白提交到條帶並清除數據或錯誤? 例如,如果const newdefault為空白,我如何確保default_source未使用空白數據更新?
我會使用過濾器命令並將它們放入數組中嗎? 這些已經在 JSON 字符串中,所以我不確定數組是否可以工作。 此外,如果所有 3 都是空白的(意思是,沒有人更新過期月份或年份,或選擇默認值,那么他們將無法點擊 function,我在我的 ZAE832E9B5BDA2699DB45F3FA 代碼中有一個 null 檢查器)
請參閱下面的代碼和注釋::
exports.updateCard = functions.https.onCall((data, context) => {
const stripeId = data.stripeId; // needed as users stripe ID
const cardId = data.cardId; // the current card they are updating, comes from the app
const month = data.expmonth; // this may or may not be blank
const year = data.expyear; // this may or may not be blank
const newdefault = data.newdefault; //this may or may not be blank
return stripe.customers.updateSource(stripeId, cardId,
{
exp_month: month, <--- how can I make sure this is not updated if month is blank?
exp_year: year <--- how can I make sure this is not updated if year is blank?
}
).then(() => {
return stripe.customers.update(stripeId,
{
default_source: newdefault <--- how can I make sure this is not updated if newdefault is blank?
}
).then(() => {
console.log(card);
return { myReturn: card };
}).catch((err) => {
console.log(err);
});
});
});
在我的研究中,我發現可以使用一個名為 array.filter 的命令。 但是,這些不是 arrays,而是 JSON 字符串。 這是我在 StackOverflow 上找到的示例以及鏈接。
StackOverflow 上關於.filter 的文章
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
有人可以告訴我是否可以使用這種方法,如果不能,請提供一個我可以用來實現的方法示例,如果變量有數據,則只允許提交條帶化。 可能是一個switch語句?
如果您僅使用基於您想要的顯式條件的屬性填充 object,它可能會更直接:
const obj = {}
if (thing) {
obj.thing = thing
}
if (otherthing) {
obj.otherthing = otherthing
}
stripe.customers.updateSource(obj)
換句話說,當您調用任何 API 時,無需一次指定整個 object。 只需根據您想要的條件構建 object。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.