generated from Lidemy/mentor-program-5th
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw2.js
110 lines (102 loc) · 2.09 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const request = require('request')
const process = require('process')
const requestUrl = 'https://lidemy-book-store.herokuapp.com/books'
if (process.argv[2] === 'list') {
list20names()
} else if (process.argv[2] === 'read') {
readBookname()
} else if (process.argv[2] === 'delete') {
deleteBook()
} else if (process.argv[2] === 'create') {
createBook()
} else if (process.argv[2] === 'update') {
updateBookname()
}
function list20names() {
request(
`${requestUrl}` + '?_limit=20',
(error, response, body) => {
// 判斷錯誤
if (error) {
console.log('err', error)
return 'error'
}
// 測試JSON字串是否合法
let json
try {
json = JSON.parse(body)
} catch (error) {
console.log(error)
}
for (let i = 0; i < json.length; i++) {
console.log(json[i].name)
}
}
)
}
function readBookname() {
request(
`${requestUrl}/${process.argv[3]}`,
(error, response, body) => {
// 判斷錯誤
if (error) {
console.log('err', error)
return 'error'
}
// 測試JSON字串是否合法
let json
try {
json = JSON.parse(body)
} catch (error) {
console.log(error)
}
console.log(json.name)
}
)
}
function deleteBook() {
request.delete(
`${requestUrl}/${process.argv[3]}`,
(error, response, body) => {
// 判斷錯誤
if (error) {
console.log('err', error)
return 'error'
}
}
)
}
function createBook() {
request.post(
{
url: `${requestUrl}`,
form: {
name: process.argv[3]
}
},
(error, response, body) => {
// 判斷錯誤
if (error) {
console.log('err', error)
return 'error'
}
}
)
}
function updateBookname() {
request.patch(
{
url: `${requestUrl}/${process.argv[3]}`,
form: {
name: process.argv[4]
}
},
(error, response, body) => {
// 判斷錯誤
if (error) {
console.log('err', error)
return 'error'
}
}
)
}