-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
96 lines (84 loc) · 2.77 KB
/
main.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
/* Moralis init code */
const serverUrl = "YOUR_SERVER_URL";
const appId = "YOUR_APP_ID";
Moralis.start({ serverUrl, appId });
var loginBtn = document.getElementById("btn-login");
var logoutBtn = document.getElementById("btn-logout");
var getBtn = document.getElementById("btn-get");
var downloadBtn = document.getElementById("btn-download");
async function getUsers() {
// request user data
userData = await Moralis.Cloud.run("userList");
// provide data in html
document.getElementById("content").innerHTML = userData;
}
async function getUsersCSV() {
// request user data
userData = await Moralis.Cloud.run("userList");
// prepare csv data
objJson = JSON.parse(userData);
if (objJson.length != 0) {
// Get all elements in array
var json = [];
for (let i = 0; i < objJson.length; i++) {
json.push(objJson[i]);
}
var fields = Object.keys(objJson[0]);
var replacer = function (key, value) { return value === null ? '' : value };
var csv = json.map(function (row) {
return fields.map(function (fieldName) {
cell = JSON.stringify(row[fieldName], replacer);
if (cell.includes(",")) {
// comma ... !
return '"' + JSON.stringify(row[fieldName], replacer).replaceAll('"', '""') + '"';
}
else {
return JSON.stringify(row[fieldName], replacer);
}
}).join(',')
});
csv.unshift(fields.join(',')); // add header column
csv = csv.join('\r\n');
}
else {
csv = "";
}
// provide the name for the CSV file to be downloaded
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'UserList.csv';
hiddenElement.click();
}
async function logIn() {
let user = Moralis.User.current();
if (!user) {
try {
user = await Moralis.authenticate();
document.getElementById("myAddress").innerHTML = user.get('ethAddress');
loginBtn.style.display = "none";
logoutBtn.style.display = "block";
} catch (error) {
console.log(error);
}
}
}
async function logOut() {
await Moralis.User.logOut();
document.getElementById("myAddress").innerHTML = "";
loginBtn.style.display = "block";
logoutBtn.style.display = "none";
}
loginBtn.onclick = logIn;
logoutBtn.onclick = logOut;
getBtn.onclick = getUsers;
downloadBtn.onclick = getUsersCSV;
if (Moralis.User.current()) {
document.getElementById("myAddress").innerHTML = Moralis.User.current().get('ethAddress');
loginBtn.style.display = "none";
logoutBtn.style.display = "block";
}
else {
loginBtn.style.display = "block";
logoutBtn.style.display = "none";
}