I have created a little function to fetch data from google analytics to display on our Hugo-based site. My problem is that the function only executes when I visit the function directly in a browser, or by sending a request. I would like it to execute during build so that Hugo can consume the generated json file.
const { google } = require("googleapis");
const fs = require("fs");
require("dotenv").config();
const PRIVATE_KEY = process.env.PRIVATE_KEY.replace(/\\n/gm, "\n");
const scopes = "https://www.googleapis.com/auth/analytics.readonly";
const jwt = new google.auth.JWT(
process.env.CLIENT_EMAIL,
null,
PRIVATE_KEY,
scopes
);
async function getData() {
const defaults = {
auth: jwt,
ids: "ga:" + process.env.VIEW_ID,
};
const response = await jwt.authorize();
const result = await google.analytics("v3").data.ga.get({
...defaults,
"start-date": "2020-04-01",
"end-date": "today",
metrics: "ga:pageviews, ga:sessions"
});
return result;
}
async function writeFile(data) {
fs.writeFile("data/ga.json", JSON.stringify(data), function (err) {
if (err) throw err;
console.log("Saved!");
});
}
exports.handler = (event, context, callback) => {
getData().then((res) => {
writeFile(res.data.totalsForAllResults)
callback(null, {
statusCode: 200,
body: JSON.stringify(res.data.totalsForAllResults),
});
});
};