【发布时间】: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