簡體   English   中英

如何將此調用緩存到 Google 表格 API?

[英]How can I cache this call to the Google Sheets API?

我已按照此處的說明使用 Google 表格作為 JSON 端點。 然后我在 Eleventy 中使用該數據。 此代碼當前正在運行:

module.exports = async function() {
  let url = `https://docs.google.com/spreadsheets/d/${process.env.GOOGLE_SHEETS_ID}/gviz/tq?tqx=out:json`;
  console.log("Fetching from Google Sheets...");
  return await fetch(url)
    .then(res => res.text()) // node-fetch option to transform to json
    .then(text => {
      let json = JSON.parse(text.substr(47).slice(0, -2));
      return {
        items: json.table.rows
      };
    });
}

...但是,這會導致構建時間變慢,因此我試圖將其與11ty 文檔中所述的eleventy-cache-assets插件聯系起來。

這是我試過的:

module.exports = async function() {
  let url = `https://docs.google.com/spreadsheets/d/${process.env.GOOGLE_SHEETS_ID}/gviz/tq?tqx=out:json`;

  var text = await Cache(url, {
    duration: "1s",
    type: "text"
  })
  .then(text => {
    var json = JSON.parse(text.substr(47).slice(0, -2));
    console.log(json);
    return {
      items: json.table.rows
    };
  });
};

在控制台中,它確實返回了 JSON,但是當我嘗試像這樣從.eleventy.js中的數據中收集數據時:

eleventyConfig.addCollection("myGSheets", (collection) => {
  return collection.getAll()[0].data.myGSheets.items;
});

我收到一個錯誤: Cannot read property 'items' of undefined

我不確定在控制台中出現的 JSON 數據與未定義數據之間發生了什么。

我猜也許我需要在調用 Cache 之前對響應進行字符串操作,也許吧? 我只是不確定如何將它們放在一起......

看起來您實際上並沒有從數據 function 中返回任何內容,因為您的return語句在回調 function 中,而不是頂級數據 function 中。

module.exports = async function() { // <= top level data function
  let url = `https://docs.google.com/spreadsheets/d/${process.env.GOOGLE_SHEETS_ID}/gviz/tq?tqx=out:json`;

  var text = await Cache(url, {
    duration: "1s",
    type: "text"
  })
  .then(text => { // <= inner callback function
    var json = JSON.parse(text.substr(47).slice(0, -2));
    console.log(json);
    return { // <= This return statement returns from the inner callback
      items: json.table.rows
    };
  });

  // <= This function doesn't return anything!
};

由於您使用的是async/await ,因此不需要使用Promise.then 你可以只等待承諾,這樣就不需要所有的回調。

嘗試:

module.exports = async function() {
  let url = `https://docs.google.com/spreadsheets/d/${process.env.GOOGLE_SHEETS_ID}/gviz/tq?tqx=out:json`;

  var text = await Cache(url, {
    duration: "1s",
    type: "text"
  })

  var json = JSON.parse(text.substr(47).slice(0, -2));
  console.log(json);
  return {
    items: json.table.rows
  };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM