繼續寫 W4 作業
- HW2: 昨天不小心把第一本書的資料刪掉了,暫時紀錄一下我寫的程式碼。
const request = require('request');
const process = require('process')
const action = process.argv[2]
const API_ENDPOINT = 'https://lidemy-book-store.herokuapp.com';
if (action === 'list') {
listBook()
} else if (action === 'read') {
readBook(process.argv[3])
} else if (action === 'delete') {
deleteBook(process.argv[3])
} else if (action === 'create') {
createBook(process.argv[3])
} else if (action === 'update') {
updateBook()
} else {
console.log('error')
}
if (action === 'createBooks') {
createBooks(process.argv[3], process.argv[4])
}
function listBook() {
request('https://lidemy-book-store.herokuapp.com/books?_limit=20',
function (error, response, body) {
if (error) {
console.log('error:', error)
return
}
let obj
try {
obj = JSON.parse(body)
} catch(error) {
console.log(error)
return
}
for (let i = 0; i < obj.length; i++) {
console.log(`${obj[i].id} ${obj[i].name}`)
}
});
}
function readBook(id) {
request('https://lidemy-book-store.herokuapp.com/books/' + id,
function (error, response, body) {
if (error) {
console.log('error:', error)
return
}
let book
try {
book = JSON.parse(body)
} catch(error) {
console.log(error)
return
}
console.log(book)
});
}
function deleteBook(id) {
request.delete('https://lidemy-book-store.herokuapp.com/books/' + id,
function (error, response, body) {
if (error) {
console.log('error:', error)
return
}
let book
try {
book = JSON.parse(body)
} catch(error) {
console.log(error)
return
}
console.log(book)
});
}
function createBook(name) {
request.post('https://lidemy-book-store.herokuapp.com/books/',
function (error, response, body) {
if (error) {
console.log('error:', error)
return
}
let book
try {
book = JSON.parse(body)
} catch(error) {
console.log(error)
return
}
console.log(book)
});
}
function updateBook(id, name) {
}
function createBooks(name) {
request.post({
url: `${API_ENDPOINT}/books`,
form: {
name
}
}, (err, res) => {
if (err) {
return console.log('新增失敗', err);
}
console.log('新增成功!');
})
}