addbook.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const https = require('https')
  2. // 新增图书 1. 获取豆瓣信息 2 入库
  3. // https://api.douban.com/v2/book/isbn/9787536692930
  4. module.exports = async (ctx) => {
  5. const { isbn, openId } = ctx.request.body
  6. console.log('添加图书', isbn, openId)
  7. if (isbn && openId) {
  8. let url = 'https://api.douban.com/v2/book/isbn/' + isbn
  9. console.log('链接', url)
  10. const bookInfo = await getJSON(url)
  11. const rate = bookInfo.rating.average
  12. const { title, image, alt, publisher, summary, price } = bookInfo
  13. const tags = bookInfo.tags.map(v => {
  14. return `${v.title} ${v.count}`
  15. }).join(',')
  16. const author = bookInfo.author.join(',')
  17. console.log({
  18. rate, title, image, alt, publisher, summary, price, tags, author
  19. })
  20. }
  21. }
  22. function getJSON (url) {
  23. return new Promise((resolve, reject) => {
  24. https.get(url, res => {
  25. let urlData = ''
  26. res.on('data', data => {
  27. urlData += data
  28. })
  29. res.on('end', data => {
  30. const bookInfo = JSON.parse(data)
  31. if (bookInfo.title) {
  32. resolve(bookInfo)
  33. }
  34. reject(bookInfo)
  35. })
  36. })
  37. })
  38. }