-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (63 loc) · 1.85 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
let messageEl = $(".message");
let usernameEl = $(".username");
let submitEl = $(".submit");
let noteListEl = $(".note-list");
const Note = skygear.Record.extend('note');
// Append to list
function addNoteToList(username, message) {
let listItem = $(`<li>${username}: ${message}</li>`);
noteListEl.append(listItem);
}
// Cloud functions
function saveNote(username, message) {
const note = new Note({ 'message': message, 'username': username });
// Save the note
skygear.publicDB.save(note).then((savedNote) => {
// The saved note at savedNote
addNoteToList(savedNote.username, savedNote.message);
}, (error) => {
console.error(error);
});
}
function loadNotes() {
const Note = skygear.Record.extend('note');
const query = new skygear.Query(Note);
skygear.publicDB.query(query).then((notes) => {
// Loop through the notes
console.log(notes);
let noteCount = notes.length;
for (let i =0; i< noteCount; i++) {
addNoteToList(notes[i].username, notes[i].message);
}
}, (error) => {
console.error(error);
});
}
// Event Handler
submitEl.on("click", function(e) {
let username = usernameEl.val();
let message = messageEl.val();
alert(`Message received! \n${usernameEl.val()}: ${messageEl.val()}`)
if (username !== "" && message !== "") {
saveNote(username, message);
}
});
// Config Skygear
skygear.config({
'endPoint': 'https://noteapp.skygeario.com/', // trailing slash is required
'apiKey': '6abbf032a68a47c1bd4ad2e703979746',
}).then(() => {
console.log('skygear container is now ready for making API calls.');
if (!skygear.auth.currentUser) {
skygear.auth.signupAnonymously().then((user) => {
console.log(user); // user record
loadNotes();
}, (error) => {
console.error(error);
});
} else {
loadNotes();
}
}, (error) => {
console.error(error);
});