如何将此调用缓存到 Google 工作表 API?

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

我按照 instructions here 使用 Google Sheet 作为 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
    };
  });
};

在控制台中,它执行 return JSON,但是当我尝试像这样从 .eleventy.js 中的数据中收集数据时:

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

我得到一个错误:Cannot read property 'items' of undefined

我不确定 JSON 数据出现在控制台中,然后未定义之间发生了什么。

我猜我可能需要在调用 Cache 之前对响应进行字符串操作,对吧?我只是不确定如何将它们放在一起...

看起来您实际上并没有从数据函数中返回任何内容,因为您的 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
  };
};