Skip to content

Instantly share code, notes, and snippets.

@cvega21
Last active August 25, 2021 01:08
Show Gist options
  • Save cvega21/ffba6ca3a9827ce22f01ab964d710de4 to your computer and use it in GitHub Desktop.
Save cvega21/ffba6ca3a9827ce22f01ab964d710de4 to your computer and use it in GitHub Desktop.
Project Data - Firebase Scheduled Function
interface projectsTimeInterface {
[key: string]: number
}
interface togglRecordInterface {
[key: string]: number | string | null | boolean | Array<string>
}
exports.getDailyData = functions.pubsub.schedule('0 4 * * *')
.timeZone('America/Mexico_City')
.onRun(async (context) => {
const getDateToLoad = async () => {
const lastLoaded = await database.ref(`/projectsMetadata/until`).get();
const lastLoadedDT = DateTime.fromISO(lastLoaded.val(), { zone: 'America/Mexico_City'});
const today = DateTime.now().setZone('America/Mexico_City');
if (lastLoaded.exists() && lastLoadedDT.startOf('day') < today.startOf('day')) {
console.log(`DB last updated at ${lastLoadedDT.toISODate()}. loading data from ${today.toISODate()}.`)
return lastLoadedDT.toISODate();
} else {
console.log(`today's data is already loaded. last updated: ${lastLoadedDT.toISODate()}`)
return ''
}
}
const setDateLoaded = async (date: string) => {
await database.ref(`/projectsMetadata/until`).set(date);
return null
}
const getFirebaseProjectData = async () => {
console.log(`getting data from Firebase...`)
const time = await (await database.ref(`/projects/`).get()).val();
return time
}
try {
const dateToLoad: string = await getDateToLoad();
const projectsDict: projectsTimeInterface = await getFirebaseProjectData();
if (dateToLoad === '') {
console.log('no changes needed. exit function...')
return null
} else {
console.log('starting daily update...')
}
const newData = await getTogglProjectData(dateToLoad, dateToLoad);
newData.data.forEach((record: togglRecordInterface) => {
let projectName = record.description as string;
let durationInMs = record.dur as number
let projectDuration = Number((durationInMs/3600000).toFixed(1));
if (projectsDict.hasOwnProperty(projectName)) {
projectsDict[projectName] = Number((projectsDict[projectName] + projectDuration).toFixed(1));
}
});
setFirebaseProjectData(projectsDict);
setDate(dateToLoad);
} catch (err) {
console.error(err);
}
return null;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment