-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanUpArchivedBooks.ts
47 lines (39 loc) · 1.32 KB
/
cleanUpArchivedBooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import {initializeApp} from "./common";
initializeApp();
/**
* Clean up archived books and records deleted a month ago.
*/
export const cleanUpArchivedBooks = functions
.scheduler
// Schedule for the 1st day of every month
// https://crontab.guru/#0_0_1_*_*
.onSchedule("0 0 1 * *", async () => {
try {
const lastMonth = Date.now() - 2629800000;
const archivedBookList = await admin
.firestore()
.collection("books")
.where("archived", "==", true)
.where("archivedOn", "<=", lastMonth)
.get();
for (const doc of archivedBookList.docs) {
// Delete the book
await doc.ref.delete();
// Delete all records
const records = await admin
.firestore()
.collection("books/" + doc.id + "/records")
.get();
const deletePromises = records.docs.map((doc) => {
return doc.ref.delete();
});
await Promise.all(deletePromises);
console.log("deleted " + records.size + " records.");
}
console.log("Deleted " + archivedBookList.size + " archived books!");
} catch (e) {
console.log(e);
}
});