Skip to content

Commit 8d40d7f

Browse files
committed
Script
1 parent 8a3a662 commit 8d40d7f

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/**
2+
* Migration: set default notification preferences on existing users that are missing them.
3+
* New users get these set at signup; this backfills everyone else.
4+
*
5+
* Defaults:
6+
* notifyPosts: true
7+
* notifyJobs: true
8+
* notifyAnnouncements: true
9+
* notifyEventsInCity: true
10+
* notifyEventsAll: false
11+
*
12+
* Run with: npx tsx scripts/migrate-notification-defaults.ts
13+
*/
14+
import { initializeApp, cert, getApps } from "firebase-admin/app";
15+
import { getFirestore } from "firebase-admin/firestore";
16+
import * as path from "path";
17+
18+
const serviceAccountPath = process.env.GOOGLE_APPLICATION_CREDENTIALS
19+
?? path.join(process.cwd(), "service-account.json");
20+
21+
if (!getApps().length) {
22+
initializeApp({ credential: cert(serviceAccountPath) });
23+
}
24+
25+
const db = getFirestore();
26+
27+
const DEFAULTS = {
28+
notifyPosts: true,
29+
notifyJobs: true,
30+
notifyAnnouncements: true,
31+
notifyEventsInCity: true,
32+
notifyEventsAll: false,
33+
};
34+
35+
async function run() {
36+
const snap = await db.collection("users").get();
37+
38+
const batch = db.batch();
39+
let count = 0;
40+
41+
for (const doc of snap.docs) {
42+
const data = doc.data();
43+
const missing: Partial<typeof DEFAULTS> = {};
44+
45+
for (const [key, defaultValue] of Object.entries(DEFAULTS) as [keyof typeof DEFAULTS, boolean][]) {
46+
if (!(key in data)) missing[key] = defaultValue;
47+
}
48+
49+
if (Object.keys(missing).length > 0) {
50+
batch.update(doc.ref, missing);
51+
count++;
52+
}
53+
}
54+
55+
if (count === 0) {
56+
console.log("All users already have notification preferences set.");
57+
return;
58+
}
59+
60+
await batch.commit();
61+
console.log(`Updated ${count} user(s) with default notification preferences.`);
62+
}
63+
64+
run().catch((err) => { console.error(err); process.exit(1); });

0 commit comments

Comments
 (0)