0
0

addbook.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. const https = require('https')
  2. const { mysql } = require('../qcloud')
  3. // 新增图书 1. 获取豆瓣信息 2 入库
  4. // https://api.douban.com/v2/book/isbn/9787536692930
  5. module.exports = async (ctx) => {
  6. const { isbn, openid } = ctx.request.body
  7. console.log('添加图书', isbn, openid)
  8. if (isbn && openid) {
  9. // 录入异常情况
  10. const findRes = await mysql('books').select().where('isbn', isbn)
  11. if (findRes.length) {
  12. ctx.state = {
  13. code: -1,
  14. data: {
  15. msg: '图书已存在'
  16. }
  17. }
  18. return
  19. }
  20. let url = 'https://api.douban.com/v2/book/isbn/' + isbn
  21. console.log('链接', url)
  22. const bookInfo = await getJSON(url)
  23. const rate = bookInfo.rating.average
  24. const { title, image, alt, publisher, summary, price } = bookInfo
  25. const tags = bookInfo.tags.map(v => {
  26. return `${v.title} ${v.count}`
  27. }).join(',')
  28. const author = bookInfo.author.join(',')
  29. try {
  30. // 写入库
  31. await mysql('books').insert({
  32. isbn, openid, rate, title, image, alt, publisher, summary, price, tags, author
  33. })
  34. ctx.state.data = {
  35. title,
  36. msg: 'success'
  37. }
  38. } catch (e) {
  39. ctx.state = {
  40. code: -1,
  41. data: {
  42. msg: '新增失败:' + e.sqlMessage
  43. }
  44. }
  45. }
  46. }
  47. }
  48. function getJSON (url) {
  49. return new Promise((resolve, reject) => {
  50. https.get(url, res => {
  51. let urlData = ''
  52. res.on('data', data => {
  53. urlData += data
  54. })
  55. res.on('end', data => {
  56. const bookInfo = JSON.parse(urlData)
  57. if (bookInfo.title) {
  58. resolve(bookInfo)
  59. }
  60. reject(bookInfo)
  61. })
  62. })
  63. })
  64. }