GetArticleList.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. const API = require("../../lib/API");
  2. const db = require("../../plugin/DataBase/db");
  3. const { BaseStdResponse } = require("../../BaseStdResponse");
  4. class GetArticleList extends API {
  5. constructor() {
  6. super();
  7. this.setPath('/Article/List')
  8. this.setMethod('GET')
  9. }
  10. async onRequest(req, res) {
  11. let { pagesize, current, type } = req.query;
  12. if ([pagesize, current, type].some(value => value === '' || value === null || value === undefined)) {
  13. return res.json({
  14. ...BaseStdResponse.MISSING_PARAMETER,
  15. endpoint: 1513126
  16. })
  17. }
  18. // 校验分页参数
  19. if (isNaN(pagesize) || pagesize <= 0) {
  20. return res.json({
  21. ...BaseStdResponse.ERR,
  22. msg: '参数错误'
  23. })
  24. }
  25. if (isNaN(current) || current <= 0) {
  26. return res.json({
  27. ...BaseStdResponse.ERR,
  28. msg: '参数错误'
  29. })
  30. }
  31. // 计算分页的 offset
  32. let offset = (current - 1) * pagesize
  33. pagesize = parseInt(pagesize, 10)
  34. offset = parseInt(offset, 10)
  35. let sql = `
  36. SELECT
  37. a.id,
  38. a.title,
  39. a.\`describe\`,
  40. a.cover,
  41. a.type,
  42. a.views,
  43. a.time,
  44. u.username AS author
  45. FROM
  46. article a
  47. LEFT JOIN
  48. users u
  49. ON
  50. a.author = u.uuid
  51. WHERE
  52. a.state = 1
  53. AND a.type = ?
  54. ORDER BY
  55. a.id DESC
  56. `
  57. // 查询文章总数,方便返回总页数
  58. let countSql = `
  59. SELECT COUNT(*) AS total
  60. FROM article a
  61. WHERE a.state = 1
  62. AND a.type = ?;
  63. `
  64. try {
  65. // 获取文章列表
  66. let articles = await db.query(sql, [type])
  67. // 获取总记录数
  68. let countResult = await db.query(countSql, [type])
  69. let total = countResult[0].total;
  70. // 计算总页数
  71. const totalPages = Math.ceil(total / pagesize)
  72. // 返回结果
  73. res.json({
  74. ...BaseStdResponse.OK,
  75. data: articles || [],
  76. pagination: {
  77. current: current,
  78. pagesize: pagesize,
  79. total: total,
  80. totalPages: totalPages
  81. }
  82. })
  83. } catch (err) {
  84. this.logger.error(`获取文章列表失败!${err.stack}`)
  85. res.json({
  86. ...BaseStdResponse.ERR,
  87. msg: '获取文章列表失败!',
  88. endpoint: 153127
  89. })
  90. }
  91. }
  92. }
  93. module.exports.GetArticleList = GetArticleList;