generated from microsoft/Web-Dev-For-Beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
246 lines (196 loc) · 6.71 KB
/
app.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const serverUrl = 'http://localhost:5000/api';
const storageKey = 'savedAccount';
// ---------------------------------------------------------------------------
// Router
// ---------------------------------------------------------------------------
const routes = {
'/dashboard': { title: 'My Account', templateId: 'dashboard', init: refresh },
'/login': { title: 'Login', templateId: 'login' }
};
function navigate(path) {
window.history.pushState({}, path, window.location.origin + path);
updateRoute();
}
function updateRoute() {
const path = window.location.pathname;
const route = routes[path];
if (!route) {
return navigate('/dashboard');
}
const template = document.getElementById(route.templateId);
const view = template.content.cloneNode(true);
const app = document.getElementById('app');
app.innerHTML = '';
app.appendChild(view);
if (typeof route.init === 'function') {
route.init();
}
document.title = route.title;
}
// ---------------------------------------------------------------------------
// API interactions
// ---------------------------------------------------------------------------
async function sendRequest(api, method, body) {
try {
const response = await fetch(serverUrl + api, {
method: method || 'GET',
headers: body ? { 'Content-Type': 'application/json' } : undefined,
body
});
return await response.json();
} catch (error) {
return { error: error.message || 'Unknown error' };
}
}
async function getAccount(user) {
return sendRequest('/accounts/' + encodeURIComponent(user));
}
async function createAccount(account) {
return sendRequest('/accounts', 'POST', account);
}
async function createTransaction(user, transaction) {
return sendRequest('/accounts/' + user + '/transactions', 'POST', transaction);
}
// ---------------------------------------------------------------------------
// Global state
// ---------------------------------------------------------------------------
let state = Object.freeze({
account: null
});
function updateState(property, newData) {
state = Object.freeze({
...state,
[property]: newData
});
localStorage.setItem(storageKey, JSON.stringify(state.account));
}
// ---------------------------------------------------------------------------
// Login/register
// ---------------------------------------------------------------------------
async function login() {
const loginForm = document.getElementById('loginForm')
const user = loginForm.user.value;
const data = await getAccount(user);
if (data.error) {
return updateElement('loginError', data.error);
}
updateState('account', data);
navigate('/dashboard');
}
async function register() {
const registerForm = document.getElementById('registerForm');
const formData = new FormData(registerForm);
const data = Object.fromEntries(formData);
const jsonData = JSON.stringify(data);
const result = await createAccount(jsonData);
if (result.error) {
return updateElement('registerError', result.error);
}
updateState('account', result);
navigate('/dashboard');
}
// ---------------------------------------------------------------------------
// Dashboard
// ---------------------------------------------------------------------------
async function updateAccountData() {
const account = state.account;
if (!account) {
return logout();
}
const data = await getAccount(account.user);
if (data.error) {
return logout();
}
updateState('account', data);
}
async function refresh() {
await updateAccountData();
updateDashboard();
}
function updateDashboard() {
const account = state.account;
if (!account) {
return logout();
}
updateElement('description', account.description);
updateElement('balance', account.balance.toFixed(2));
updateElement('currency', account.currency);
// Update transactions
const transactionsRows = document.createDocumentFragment();
for (const transaction of account.transactions) {
const transactionRow = createTransactionRow(transaction);
transactionsRows.appendChild(transactionRow);
}
updateElement('transactions', transactionsRows);
}
function createTransactionRow(transaction) {
const template = document.getElementById('transaction');
const transactionRow = template.content.cloneNode(true);
const tr = transactionRow.querySelector('tr');
tr.children[0].textContent = transaction.date;
tr.children[1].textContent = transaction.object;
tr.children[2].textContent = transaction.amount.toFixed(2);
return transactionRow;
}
function addTransaction() {
const dialog = document.getElementById('transactionDialog');
dialog.classList.add('show');
// Reset form
const transactionForm = document.getElementById('transactionForm');
transactionForm.reset();
// Set date to today
transactionForm.date.valueAsDate = new Date();
}
async function confirmTransaction() {
const dialog = document.getElementById('transactionDialog');
dialog.classList.remove('show');
const transactionForm = document.getElementById('transactionForm');
const formData = new FormData(transactionForm);
const jsonData = JSON.stringify(Object.fromEntries(formData));
const data = await createTransaction(state.account.user, jsonData);
if (data.error) {
return updateElement('transactionError', data.error);
}
// Update local state with new transaction
const newAccount = {
...state.account,
balance: state.account.balance + data.amount,
transactions: [...state.account.transactions, data]
}
updateState('account', newAccount);
// Update display
updateDashboard();
}
async function cancelTransaction() {
const dialog = document.getElementById('transactionDialog');
dialog.classList.remove('show');
}
function logout() {
updateState('account', null);
navigate('/login');
}
// ---------------------------------------------------------------------------
// Utils
// ---------------------------------------------------------------------------
function updateElement(id, textOrNode) {
const element = document.getElementById(id);
element.textContent = ''; // Removes all children
element.append(textOrNode);
}
// ---------------------------------------------------------------------------
// Init
// ---------------------------------------------------------------------------
function init() {
// Restore state
const savedState = localStorage.getItem(storageKey);
if (savedState) {
updateState('account', JSON.parse(savedState));
}
// Update route for browser back/next buttons
window.onpopstate = () => updateRoute();
updateRoute();
}
init();