没有cmc匹配时,Google会覆盖不正确的范围宽度

时间:2018-06-07 23:17:28

标签: javascript google-sheets-api

我正在使用此功能使用他们的v2 api从coinmarketcap中提取信息。我得到的问题是,如果coinmarketcap上不存在“website_slug”,我会收到incorrect range width错误而不是将xxx放入单元格中的函数。这可以通过让B列中的单元格与cmc(https://api.coinmarketcap.com/v2/ticker/)上的website_slug不匹配来重新创建。

function getMarketCap(sheetname) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetname);  
  var assets = [];  
  var idRange = sheet.getRange("B1:B");
  var lastRow = getLastRowOfRange(idRange);  
  var cellRange = sheet.getRange(1, 2, lastRow).getValues();
  var mcRange = sheet.getRange(1, 3, lastRow);  
  var mcValues = [];  
  for (var i = 0; i < cellRange.length; i++) {
    assets[i] = cellRange[i];
  }  


  var req = [];
  for (var i = 0; i < 16; i++) {
    req.push({
      muteHttpExceptions: true,
      method: "get",
      url: "https://api.coinmarketcap.com/v2/ticker/?start=" + (i * 100 + 1),
    });
  }
  var responses = UrlFetchApp.fetchAll(req);
  var res = responses.filter(function(e){return e.getResponseCode() == 200}).map(function(e){return JSON.parse(e.getContentText())});
  if (responses.length != res.length) Logger.log("%s errors occurred.", responses.length - res.length);
  var mcValues = [];
  assets.forEach(function(e, h) {
    mcValues[h] = []
    res.some(function(f) {
      Object.keys(f.data).some(function(g) {
        if (f.data[g].website_slug == e[0]) {
          mcValues[h][0] = f.data[g].quotes.USD.market_cap;
          return true;
        }
      });
      if (mcValues[h][0]) return true;
    });
    if (!mcValues[h][0]) mcValues[h][0] = 'xxx';

  });

  mcRange.setValues(mcValues); 
}

0 个答案:

没有答案