【问题标题】:How can I cache this call to the Google Sheets API?如何将此调用缓存到 Google Sheets API?
【发布时间】:2021-10-24 02:40:03
【问题描述】:

我已按照instructions here 使用 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
      };
    });
}

...但是,这会导致构建时间变慢,因此我尝试将其与eleventy-cache-assets 插件联系起来,如11ty docs 中所述。

这是我尝试过的:

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 之前对响应进行字符串操作,也许?我只是不确定如何将它们放在一起......

【问题讨论】:

    标签: javascript google-sheets eleventy


    【解决方案1】:

    看起来您实际上并没有从数据函数返回任何内容,因为您的 return 语句位于回调函数内部,而不是顶级数据函数。

    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
      };
    };
    

    【讨论】:

    • 谢谢;有用!这一切都很有意义,这意味着我需要更好地了解我的基本 JS 理解。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-09-25
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多