Skip to content

Instantly share code, notes, and snippets.

@rosswintle
Last active November 7, 2021 20:46
Show Gist options
  • Save rosswintle/4d2c8ea8d211770e4ff319e65b97d711 to your computer and use it in GitHub Desktop.
Save rosswintle/4d2c8ea8d211770e4ff319e65b97d711 to your computer and use it in GitHub Desktop.
Code to show daily pageviews from the Fathom API in an iOS widget using the Scriptable app
/**
* @returns {string}
*/
function getApiKey() {
return '<YOUR_API_KEY>';
}
/**
* @returns {Promise}
*/
async function getSites() {
const sitesRequest = new Request( 'https://api.usefathom.com/v1/sites' )
sitesRequest.headers = { 'Authorization': 'Bearer ' + getApiKey() }
const sitesResult = await sitesRequest.loadJSON()
return sitesResult.data;
}
/**
* @param {string} siteId
* @returns {Promise}
*/
async function getPageViews(siteId) {
const pageviewsRequest = new Request( 'https://api.usefathom.com/v1/aggregations?entity=pageview&entity_id=' + siteId + '&aggregates=pageviews&date_grouping=day&sort_by=timestamp:desc&limit=1' )
pageviewsRequest.headers = { 'Authorization': 'Bearer ' + getApiKey() }
const pageviewsResult = await pageviewsRequest.loadJSON()
return parseInt(pageviewsResult[0].pageviews, 10);
}
const siteId = args.widgetParameter ? args.widgetParameter : null;
const widget = new ListWidget();
if (siteId) {
sites = await getSites();
let pageViews = await getPageViews(siteId);
let thisSite = sites.find( site => site.id === siteId );
let siteNameText = widget.addText(thisSite.name);
widget.addSpacer(8);
let viewsNumberText = widget.addText(String(pageViews));
viewsNumberText.font = Font.semiboldSystemFont(64);
let viewsLabelText = widget.addText(' views today');
} else {
widget.addText('No site specified - please update widget settings');
}
Script.setWidget(widget)
widget.presentMedium()
Script.complete();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment