generated from RealDevSquad/website-template
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathuserMigrations.js
More file actions
63 lines (56 loc) · 1.86 KB
/
userMigrations.js
File metadata and controls
63 lines (56 loc) · 1.86 KB
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
const firestore = require("../utils/firestore");
const userModel = firestore.collection("users");
const { getRandomIndex } = require("../utils/helpers");
export const MAX_TRANSACTION_WRITES = 499;
const USER_COLORS = 10;
/**
* Returns the object with details about users to whom user color was added
*
* @param req {Object} - Express request object
* @param res {Object} - Express response object
*/
const addDefaultColors = async (batchSize = MAX_TRANSACTION_WRITES) => {
try {
if (batchSize > MAX_TRANSACTION_WRITES) {
throw new Error(`Error cannot add more than ${batchSize} users at once .`);
}
const usersSnapshot = await userModel.get();
const usersArr = [];
usersSnapshot.forEach((doc) => usersArr.push({ id: doc.id, ...doc.data() }));
const batchArray = [];
const users = [];
batchArray.push(firestore.batch());
let operationCounter = 0;
let batchIndex = 0;
let totalCount = 0;
for (const user of usersArr) {
const colors = user.colors ?? {};
if (!user.colors) {
const userColorIndex = getRandomIndex(USER_COLORS);
colors.color_id = userColorIndex;
const docId = userModel.doc(user.id);
batchArray[parseInt(batchIndex)].set(docId, { ...user, colors });
operationCounter++;
totalCount++;
users.push(user.username);
if (operationCounter === MAX_TRANSACTION_WRITES) {
batchArray.push(firestore.batch());
batchIndex++;
operationCounter = 0;
}
}
}
batchArray.forEach(async (batch) => await batch.commit());
return {
totalUsersFetched: usersArr.length,
totalUsersUpdated: totalCount,
totalUsersUnaffected: usersArr.length - totalCount,
};
} catch (err) {
logger.error("Error adding default colors to users", err);
throw err;
}
};
module.exports = {
addDefaultColors,
};