generated from Lidemy/mentor-program-5th
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw2.js
88 lines (84 loc) · 2.21 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const request = require('request')
const API = 'https://lidemy-book-store.herokuapp.com'
const bookAPI = {
list() {
const limit = 20
request.get(`${API}/books?_limit=${limit}`, (err, res, body) => {
if (err) return console.log('catch error', err)
if (res.statusCode >= 200 && res.statusCode < 300) {
const bookData = JSON.parse(body)
this.render(bookData)
}
})
},
read(id) {
request.get(`${API}/books/${id}`, (err, res, body) => {
if (err) return console.log('catch error', err)
if (res.statusCode >= 200 && res.statusCode < 300) {
const bookData = JSON.parse(body)
this.render(bookData)
} else {
console.log(`can't find ${id}`)
}
})
},
create(name) {
request.post(
{
url: `${API}/books`,
form: { name }
},
(err, res, body) => {
if (err) return console.log('catch error', err)
if (res.statusCode >= 200 && res.statusCode < 300) {
const bookData = JSON.parse(body)
this.render(bookData)
}
}
)
},
delete(id) {
request.delete(`${API}/books/${id}`, (err, res, body) => {
if (err) return console.log('catch error', err)
if (res.statusCode >= 200 && res.statusCode < 300) {
console.log(`delete book id:${id} ok`)
} else {
console.log(`can't find book id:${id}`)
}
})
},
update(id, name) {
request.patch(
{
url: `${API}/books/${id}`,
form: { name }
},
(err, res, body) => {
if (err) return console.log('catch error', err)
if (res.statusCode >= 200 && res.statusCode < 300) {
const bookData = JSON.parse(body)
this.render(bookData)
} else {
console.log(`can't find book id:${id}`)
}
}
)
},
render(bookData) {
if (bookData.length) {
for (const book of bookData) {
console.log(`${book.id} ${book.name}`)
}
} else {
console.log(`${bookData.id} ${bookData.name}`)
}
}
}
const action = process.argv[2]
const param1 = process.argv[3]
const param2 = process.argv[4]
try {
bookAPI[action](param1, param2)
} catch (error) {
console.log("can't find action")
}