-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
102 lines (85 loc) · 2.68 KB
/
index.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
///////////////////////////////////////////////////////////
var client = new faunadb.Client({ secret: 'FAUNADB_SECRET_HERE' });
var q = faunadb.query;
var faunaData = [];
///////////////////////////////////////////////////////////
function getData(){
client.query(q.Paginate(q.Match(q.Index('people_index'))))
.then((response) => {
const allRefValues = response.data.map((ref) => {
return q.Get(ref)
})
return client.query(allRefValues).then((data) => {
console.log(data);
faunaData = data;
populateUI();
})
})
.catch(err => console.warn(err))
}
function addData() {
var random = Math.floor(Math.random() * (999 - 100) + 100);
client.query(q.Create(q.Collection('people'), {
data: {
firstName: "John" + random,
lastName: "Smith" + random
},}))
.then(res => {
console.log(res);
faunaData.push(res);
populateUI();
})
.catch(err => console.warn(err))
}
function updateData(refID, freshData) {
client.query(q.Update(q.Ref(q.Collection('people'), refID), {
data: freshData
},))
.then((res) => {
console.log(res);
populateUI();
})
.catch(err => console.warn(err))
}
function deleteData(refID) {
client.query(q.Delete(q.Ref(q.Collection('people'), refID)))
.then(res => {
console.log(res);
populateUI();
})
.catch(err => console.warn(err.message))
}
///////////////////////////////////////////////////////////
function populateUI() {
var dataOutput = "";
for(var i=0; i < faunaData.length; i++) {
var uniqueID = faunaData[i].ref.value.id;
var person = faunaData[i].data;
dataOutput += `<div>${uniqueID} - ${person.firstName} ${person.lastName}</div>`;
}
if(faunaData.length === 0) {
dataOutput = "No records found";
}
document.getElementById("data").innerHTML = dataOutput;
}
function updateSecondRecord(){
if(faunaData.length < 2) {
alert("Add more records first");
return false;
}
var random = Math.floor(Math.random() * (999 - 100) + 100);
faunaData[1].data.lastName = "Jonas" + random;
updateData(faunaData[1].ref.value.id, faunaData[1].data);
}
function deleteThirdRecord() {
if(faunaData.length < 2) {
alert("Add more records first");
return false;
}
var thirdPerson = faunaData[2];
faunaData.splice(2, 1);
deleteData(thirdPerson.ref.value.id);
}
window.addEventListener('load', function() {
populateUI();
})