-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
89 lines (76 loc) · 2.1 KB
/
user.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
const nbApis = require('./apis.js');
const nbDatabase = require('./database.js');
const nbMessage = require('./message.js');
let Users = null;
const ensureCollectionExists = (collection) => {
if (!Users) {
Users = nbDatabase.getCollection(collection);
}
};
const welcomeNewUser = (senderID, user) => {
nbMessage.sendTextMessage([senderID], `Hello ${user.first_name} :)\n\n I am here to help you, see how by writting '!help'`);
};
const saveExtraData = (senderID, user) => {
Users.update({
senderID,
}, {
$set: {
first_name: user.first_name,
last_name: user.last_name,
},
});
};
const ensureUserExists = (senderID) => {
ensureCollectionExists('users');
Users.update({
senderID,
}, {
$setOnInsert: {
senderID,
notifications: true,
},
}, {
upsert: true,
}, (err, command) => {
if (err) {
console.log('something went wrong with the database ', err);
}
if (command.result.upserted) {
nbApis.userData(senderID, (userData) => {
saveExtraData(senderID, userData);
welcomeNewUser(senderID, userData);
});
}
});
};
const toggleNofitications = (senderID) => {
ensureCollectionExists('users');
Users.findOne({
senderID,
}, (err, user) => {
// todo make a function that hanles all these stupid errors.
if (err) {
console.log('something went wrong with the database ', err);
}
Users.update({
senderID,
}, {
$set: {
notifications: !user.notifications,
},
}, (updateErr) => {
// todo make a function that hanles all these stupid errors.
if (updateErr) {
console.log('something went wrong with the database ', updateErr);
}
let updatesStatus = 'enabled';
// we do it like so because we check the value before update.
if (user.notifications === true) {
updatesStatus = 'disabled';
}
nbMessage.sendTextMessage([senderID], `Notifications are now ${updatesStatus}`);
});
});
};
module.exports.toggleNofitications = toggleNofitications;
module.exports.ensureUserExists = ensureUserExists;