generated from Real-Dev-Squad/website-template
-
Notifications
You must be signed in to change notification settings - Fork 201
/
wallets.js
77 lines (73 loc) · 1.8 KB
/
wallets.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
const { INITIAL_WALLET } = require("../constants/wallets");
const firestore = require("../utils/firestore");
const walletModel = firestore.collection("wallets");
/**
* Fetches the data from user wallet
* @return {Promise<walletModel|object>}
*/
const fetchWallet = async (userId) => {
try {
const walletDocs = await walletModel.where("userId", "==", userId).limit(1).get();
const [userWallet] = walletDocs.docs;
if (userWallet) {
return { id: userWallet.id, ...userWallet.data() };
}
return null;
} catch (err) {
logger.error("Error retrieving wallets", err);
throw err;
}
};
/**
* Create new wallet for user
* @return {Promise<walletModel|object>}
*/
const createWallet = async (userId, currencies = {}) => {
try {
const walletData = {
userId,
isActive: true,
currencies,
};
const { id } = await walletModel.add(walletData);
return {
id,
data: walletData,
};
} catch (err) {
logger.error("Error creating user wallet", err);
throw err;
}
};
/**
* Update wallet for user
* @return {Promise<walletModel|object>}
*/
const updateWallet = async (userId, currencies) => {
try {
let userWallet = await fetchWallet(userId);
if (!userWallet) {
userWallet = await createWallet(userId, INITIAL_WALLET);
}
const firestoreKeysObject = {};
for (const key in currencies) {
firestoreKeysObject[`currencies.${key}`] = currencies[`${key}`];
}
const walletRef = walletModel.doc(userWallet.id);
const res = await walletRef.update({
...firestoreKeysObject,
});
if (res) {
return true;
}
return false;
} catch (err) {
logger.error("Error updating currency to user wallets", err);
throw err;
}
};
module.exports = {
fetchWallet,
updateWallet,
createWallet,
};