feat: reset views & monthViews
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
const { onSchedule } = require('firebase-functions/v2/scheduler')
|
||||
const { db } = require('../index')
|
||||
|
||||
|
||||
exports.resetMonthViews = onSchedule(
|
||||
{
|
||||
schedule: '0 0 1 * *',
|
||||
timeZone: 'Europe/Paris',
|
||||
timeoutSeconds: 540,
|
||||
memory: '512MiB',
|
||||
},
|
||||
async (event) => {
|
||||
console.log('Starting monthly reset of project views...')
|
||||
|
||||
const projectsRef = db.collection('projects')
|
||||
const bulkWriter = db.bulkWriter()
|
||||
|
||||
bulkWriter.onWriteError((error) => {
|
||||
console.error('Failed to write document:', error.documentRef.path, error.error)
|
||||
return false // Do not retry indefinitely for this use case
|
||||
})
|
||||
|
||||
try {
|
||||
const stream = projectsRef.stream()
|
||||
|
||||
let count = 0
|
||||
for await (const doc of stream) {
|
||||
const docRef = db.collection('projects').doc(doc.id)
|
||||
|
||||
bulkWriter.update(docRef, { monthViews: 0 })
|
||||
count++
|
||||
}
|
||||
|
||||
await bulkWriter.close()
|
||||
console.log(`Successfully scheduled reset for ${count} projects.`)
|
||||
} catch (error) {
|
||||
console.error('Error in resetMonthViews:', error)
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -57,6 +57,9 @@ exports.onProjectWritten = onDocumentWritten('projects/{projectId}', async (proj
|
||||
.doc(projectId)
|
||||
.collection('monthlyListens')
|
||||
.doc(monthKey)
|
||||
const projectsRef = refList.projects.doc(projectId)
|
||||
|
||||
|
||||
const totalsDocRef = refList.projectStreamStatsMonthlyTotals.doc(monthKey)
|
||||
|
||||
await db.runTransaction(async (transaction) => {
|
||||
@@ -78,6 +81,7 @@ exports.onProjectWritten = onDocumentWritten('projects/{projectId}', async (proj
|
||||
}
|
||||
|
||||
transaction.set(statsDocRef, updatePayload, { merge: true })
|
||||
transaction.set(projectsRef, { monthViews: FieldValue.increment(delta) }, { merge: true })
|
||||
|
||||
const totalsUpdatePayload = {
|
||||
monthKey,
|
||||
|
||||
Reference in New Issue
Block a user