访问不存在的属性的安全方法

问题描述 投票:0回答:2

我正在使用带有JavaScript代码的Google Apps脚本运行UrlFetchApp,从Stripe API中提取数据以检索发票。然后,脚本将API中的数据更新为Google Sheet模板。

我遇到的问题是,如果API在客户的特定行上没有数据,则会破坏脚本。 API将缺少的数据存储为NULL,例如,当客户在发票上没有折扣时,"discount": null

当脚本在没有数据的情况下命中行时,NULL响应会破坏脚本并停止运行。我想要做的是返回一个值,指定没有数据(例如:返回数字0表示没有折扣)并保持脚本在剩余的代码行中运行。

我的代码:

function getInvoiceObj() 
  {
    var apiKey, content, options, response, secret, url;

    secret = "rk_live_xxxxxxxxxxxxxxxxxx";
    apiKey = "xxxxxxxxxxxxxxxxx";

    url = "https://api.stripe.com/v1/invoices/in_xxxxxxxxxxxxx?expand[]=charge&expand[]=customer";

    options = {
      "method" : "GET",
      "headers": {
        "Authorization": "Bearer " + secret 
      },
      "muteHttpExceptions":true
    };

    response = UrlFetchApp.fetch(url, options);

    //Push data to Sheet from invoice. **Writes over existing Sheet data**
    content = JSON.parse(response.getContentText());
    var sheet = SpreadsheetApp.getActiveSheet();

     /* Customer Discount */

sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);
}
javascript json stripe-payments urlfetch
2个回答
1
投票

你可能正在寻找if

if(content.discount===null)
  sheet.getRange(21,2).setValue([0]);
else
  sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]);

也许?:

sheet.getRange(21,2).setValue([
  content.discount===null?0:content.discount.coupon.percent_off
]);

1
投票

这有点棘手,并且从现在开始受到多年的影响,你的问题是coupon中不存在discount因此无法从未定义的属性中获取任何值(因此脚本中断),有几种技术可以从中访问属性不存在的对象,例如:

  • try...catch结构 try { sheet.getRange(21,2).setValue([content.discount.coupon.percent_off]); } catch() { sheet.getRange(21,2).setValue([0]); }
  • 可选对象传递 const discountValue = ((content.discount || {}).coupon || {}).percent_off || 0; sheet.getRange(21,2).setValue([discountValue]);
  • 嵌套存在 const discountValue = (content.discount && content.discount.coupon && content.discount.coupon.percent_off) || 0; sheet.getRange(21,2).setValue([discountValue]);
  • 对属性访问的一些抽象 const getPropertySafe = (props, object) => props.reduce((xs, x) => (xs && xs[x]) ? xs[x] : null, object) const value = getPropertySafe(['discount', 'coupon', 'percent_off'], content) sheet.getRange(21,2).setValue([value || 0]);

不过,很快就会等待The Existential Operator

content.discount?.coupon?.percent_off || 0

© www.soinside.com 2019 - 2024. All rights reserved.