GetArticleList.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. pagesize = parseInt(pagesize, 10);
  19. current = parseInt(current, 10);
  20. if (isNaN(pagesize) || pagesize <= 0 || isNaN(current) || current <= 0) {
  21. return res.json({ ...BaseStdResponse.ERR, msg: '参数错误' });
  22. }
  23. const offset = (current - 1) * pagesize;
  24. const sql = `
  25. SELECT
  26. a.slug,
  27. a.title,
  28. a.\`describe\`,
  29. a.cover,
  30. a.type,
  31. a.views,
  32. a.time,
  33. u.username AS author
  34. FROM article a
  35. LEFT JOIN users u ON a.author = u.uuid
  36. WHERE a.state = 1 AND a.type = ?
  37. ORDER BY a.id DESC
  38. LIMIT ? OFFSET ?
  39. `;
  40. const countSql = `
  41. SELECT COUNT(*) AS total
  42. FROM article a
  43. WHERE a.state = 1 AND a.type = ?
  44. `;
  45. try {
  46. const articles = await db.query(sql, [type, String(pagesize), String(offset)]);
  47. const countResult = await db.query(countSql, [type]);
  48. const total = countResult[0].total;
  49. const totalPages = Math.ceil(total / pagesize);
  50. res.json({
  51. ...BaseStdResponse.OK,
  52. data: articles || [],
  53. pagination: {
  54. current,
  55. pagesize,
  56. total,
  57. totalPages
  58. }
  59. });
  60. } catch (err) {
  61. this.logger.error(`获取文章列表失败!${err.stack}`);
  62. res.json({
  63. ...BaseStdResponse.ERR,
  64. msg: '获取文章列表失败!',
  65. endpoint: 153127
  66. });
  67. }
  68. }
  69. }
  70. module.exports.GetArticleList = GetArticleList;