-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw2.js
74 lines (67 loc) · 1.57 KB
/
hw2.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
const request = require('request');
const process = require('process');
const apiUrl = 'https://lidemy-book-store.herokuapp.com/';
const command = process.argv[2];
const content = process.argv[3];
const patchChange = process.argv[4];
const list = () => {
request({
url: `${apiUrl}books?_limit=20`,
}, (error, body) => {
if (error) {
console.log('error');
return;
}
const data = JSON.parse(body);
for (let i = 0; i < data.length; i += 1) {
console.log(`${data[i].id} ${data[i].name}`);
}
});
};
const read = (id) => {
request({
url: `${apiUrl}/books/${id}`,
}, (error, body) => {
if (error) {
console.log('error');
return;
}
const data = JSON.parse(body);
console.log(data);
});
};
const create = (bookName) => {
request.post(`${apiUrl}books/`, { form: { name: `${bookName}` } });
};
const deleteBook = (id) => {
request.delete(`${apiUrl}books/${id}`, (error) => {
if (error) {
console.log('error');
return;
}
console.log(`Book ID: ${id} has been deleted`);
});
};
const update = (id, newName) => {
request.patch(`${apiUrl}books/${id}`, { form: { name: `${newName}` } });
console.log(`Book ID: ${id} has been updated`);
};
switch (command) {
case 'list':
list();
break;
case 'read':
read(content);
break;
case 'create':
create(content);
break;
case 'delete':
deleteBook(content);
break;
case 'update':
update(content, patchChange);
break;
default:
console.log('Availiable commands: list, read, create, delete, update');
}