Skip to content

Instantly share code, notes, and snippets.

@jamesdoc
Created January 15, 2022 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesdoc/11a91c4d8bf751be55cb5ba26171aeb2 to your computer and use it in GitHub Desktop.
Save jamesdoc/11a91c4d8bf751be55cb5ba26171aeb2 to your computer and use it in GitHub Desktop.
require("dotenv").config();
const { AssetCache } = require("@11ty/eleventy-cache-assets");
const Airtable = require("airtable");
// You configure here…
const airtableBaseId = "{{ GET ME FROM AIRTABLE }}";
const airtableTable = "{{ NAME OF YOUR TABLE }}";
const airtableTableView = "{{ THE VIEW YOU WANT TO PULL FROM }}";
const assetCacheId = "airtableCMS";
var base = new Airtable({ apiKey: process.env.AIRTABLE_API }).base(
airtableBaseId
);
module.exports = () => {
let asset = new AssetCache(assetCacheId);
// Cache the data in 11ty for one day
if (asset.isCacheValid("1d")) {
console.log("Serving airtable data from the cache…");
return asset.getCachedValue();
}
// The 11ty cache is cold… so we need to talk to Airtable
return new Promise((resolve, reject) => {
let allDatasets = [];
base(airtableTable)
.select({
view: airtableTableView,
// optional sorting params
sort: [{ field: "date", direction: "asc" }],
})
.eachPage(
function page(records, fetchNextPage) {
records.forEach((record) => {
allDatasets.push({
id: record._rawJson.id,
...record._rawJson.fields,
});
});
fetchNextPage();
},
function done(err) {
if (err) {
reject(err);
} else {
// Put the data into the 11ty cache
asset.save(allDatasets, "json");
resolve(allDatasets);
}
},
);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment