-
Notifications
You must be signed in to change notification settings - Fork 457
/
onDelete.f.js
108 lines (93 loc) · 2.93 KB
/
onDelete.f.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { database } from 'firebase-functions'
import admin from 'firebase-admin'
import moment from 'moment'
import usersUtil from 'firebase-function-tools/lib/users'
export default database.ref('/users_count').onDelete((data, context) => {
const getDBUsers = admin
.database()
.ref('users')
.once('value')
const getAuthUsers = usersUtil.listAllUsers()
return Promise.all([getDBUsers, getAuthUsers]).then(resulsts => {
const dbUsers = resulsts[0]
const authUsers = resulsts[1]
let promises = []
let userUids = []
let providerCount = {}
let usersPublicData = {}
let usersNotificationTokens = {}
authUsers.forEach(userRecord => {
const user = userRecord.toJSON()
let userPublicProviderData = {}
const creationTime = moment(user.metadata.creationTime)
const creationTimeFormated = creationTime.toISOString()
// Collecting data for provider
if (user.providerData) {
user.providerData.forEach((provider, i) => {
// Counting providers
const providerId = provider.providerId.replace('.com', '')
const current = providerCount[providerId] || 0
providerCount[providerId] = current + 1
// TO DO sanitise also the registration per month and day counter
// Collecting public provider data
userPublicProviderData[i] = {
displayName: provider.displayName ? provider.displayName : null,
providerId: provider.providerId,
}
})
}
// Collecting users public data
const userUid = user.uid
const userPublicData = {
displayName: user.displayName ? user.displayName : null,
photoURL: user.photoURL ? user.photoURL : null,
providerData: userPublicProviderData,
creationTime: creationTimeFormated,
}
usersPublicData[userUid] = userPublicData
userUids.push(userUid)
})
console.log(userUids)
// Remove unsynced users
dbUsers.forEach(userSnap => {
if (userUids.indexOf(userSnap.key) > -1) {
usersNotificationTokens[userSnap.key] = userSnap
.child('notificationTokens')
.val()
} else {
console.log(`Delete user ${userSnap.key}`)
promises.push(
admin
.database()
.ref(`users/${userSnap.key}`)
.remove()
)
promises.push(
admin
.database()
.ref(`notification_tokens/${userSnap.key}`)
.remove()
)
}
})
promises.push(
admin
.database()
.ref('provider_count')
.set(providerCount),
admin
.database()
.ref('users')
.set(usersPublicData),
admin
.database()
.ref('notification_tokens')
.set(usersNotificationTokens),
admin
.database()
.ref('users_count')
.set(authUsers.length)
)
return Promise.all(promises)
})
})