-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path4-2.app.js
More file actions
54 lines (42 loc) · 1.65 KB
/
4-2.app.js
File metadata and controls
54 lines (42 loc) · 1.65 KB
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
var server = function (method, path) {
var body = arguments.length === 4 ? arguments [2] : undefined;
var cb = arguments.length === 4 ? arguments [3] : arguments [2];
if (! cb) cb = function () {};
var reply = function (code, body) {
setTimeout (function () {
if (code >= 400) return cb (body);
else return cb (null, body);
}, 10);
}
if (method !== 'GET' && method !== 'POST') return reply (400, {error: 'Invalid method: ' + method});
if (method === 'GET' && (path !== '/products' && path !== '/cart')) return reply (404, {error: 'Path not found'});
if (method === 'POST' && path !== '/cart') return reply (404, {error: 'Path not found'});
if (method === 'GET' && path === '/products') {
return reply (200, [
{id: 1, name: 'banana', image: 'banana.png', price: 3},
{id: 2, name: 'book', image: 'book.png', price: 5},
{id: 3, name: 'car', image: 'car.png', price: 80},
{id: 4, name: 'table', image: 'table.png', price: 25},
{id: 5, name: 'tree', image: 'banana.png', price: 40},
]);
}
if (method === 'GET' && path === '/cart') {
var cart = localStorage.getItem ('cart');
if (cart) cart = JSON.parse (cart);
else cart = [];
reply (200, cart);
}
if (method === 'POST' && path === '/cart') {
localStorage.setItem ('cart', JSON.stringify (body));
reply (200, '');
}
}
var loadProducts = function (cb) {
server ('GET', '/products', cb);
}
var saveCart = function (cart, cb) {
server ('POST', '/cart', cart, cb);
}
var loadCart = function (cb) {
server ('GET', '/cart', cb);
}