繁体   English   中英

在 Node JS 中仅使用包含数据的变量的正确方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM