articles.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. const express = require('express');
  2. const router = express.Router();
  3. const {Article, Category} = require('../../models')
  4. const {Op} = require('sequelize')
  5. /**
  6. * @api {get} /admin/articles 查询文章列表
  7. * @apiName GetArticles
  8. * @apiGroup Articles
  9. * @apiVersion 1.0.0
  10. *
  11. * @apiDescription 获取文章列表,支持分页和多条件筛选
  12. *
  13. * @apiParam {Number} [currentPage=1] 当前页码,默认为1
  14. * @apiParam {Number} [pageSize=10] 每页显示数量,默认为10
  15. * @apiParam {String} [title] 标题搜索关键词(模糊匹配)
  16. * @apiParam {String|Array} [cropIds] 作物筛选ID,支持逗号分隔的多个ID或数组形式
  17. * @apiParam {Number} [categoryId] 用户分类ID,根据用户传递的category参数值进行精确匹配
  18. * @apiParam {Number} [isRecommended] 推荐筛选,0-非推荐文章,1-推荐文章
  19. *
  20. * @apiSuccess {Boolean} status 请求状态
  21. * @apiSuccess {String} message 响应消息
  22. * @apiSuccess {Object} data 响应数据
  23. * @apiSuccess {Array} data.articles 文章列表
  24. * @apiSuccess {Number} data.articles.id 文章ID
  25. * @apiSuccess {String} data.articles.title 文章标题
  26. * @apiSuccess {String} [data.articles.subtitle] 文章副标题
  27. * @apiSuccess {String} data.articles.content 文章内容
  28. * @apiSuccess {Number} data.articles.type 文章类型
  29. * @apiSuccess {String} [data.articles.img] 文章图片
  30. * @apiSuccess {Date} [data.articles.date] 文章日期
  31. * @apiSuccess {String} [data.articles.author] 作者
  32. * @apiSuccess {Number} data.articles.category 用户分类ID
  33. * @apiSuccess {Number} data.articles.crop 作物分类ID
  34. * @apiSuccess {Number} data.articles.isRecommended 是否推荐(0-不推荐,1-推荐)
  35. * @apiSuccess {String} [data.articles.seoKeyword] SEO关键词
  36. * @apiSuccess {String} [data.articles.seoDescription] SEO描述
  37. * @apiSuccess {Date} data.articles.createdAt 创建时间
  38. * @apiSuccess {Date} data.articles.updatedAt 更新时间
  39. * @apiSuccess {Object} [data.articles.cropInfo] 作物信息
  40. * @apiSuccess {Number} data.articles.cropInfo.id 作物ID
  41. * @apiSuccess {String} data.articles.cropInfo.name 作物名称
  42. * @apiSuccess {Number} data.articles.cropInfo.level 作物层级
  43. * @apiSuccess {Number} data.articles.cropInfo.parentId 父级作物ID
  44. * @apiSuccess {Object} data.pagination 分页信息
  45. * @apiSuccess {Number} data.pagination.total 总数量
  46. * @apiSuccess {Number} data.pagination.currentPage 当前页码
  47. * @apiSuccess {Number} data.pagination.pageSize 每页数量
  48. *
  49. * @apiSuccessExample {json} Success-Response:
  50. * HTTP/1.1 200 OK
  51. * {
  52. * "status": true,
  53. * "message": "成功",
  54. * "data": {
  55. * "articles": [
  56. * {
  57. * "id": 96,
  58. * "title": "测试文章",
  59. * "subtitle": "副标题",
  60. * "content": "<p>文章内容</p>",
  61. * "type": 1,
  62. * "img": null,
  63. * "date": null,
  64. * "author": "作者",
  65. * "category": 1,
  66. * "crop": 43,
  67. * "isRecommended": 1,
  68. * "seoKeyword": null,
  69. * "seoDescription": null,
  70. * "createdAt": "2025-09-14T09:21:24.000Z",
  71. * "updatedAt": "2025-09-14T09:21:24.000Z",
  72. * "cropInfo": {
  73. * "id": 43,
  74. * "name": "荔枝",
  75. * "level": 2,
  76. * "parentId": 40
  77. * }
  78. * }
  79. * ],
  80. * "pagination": {
  81. * "total": 19,
  82. * "currentPage": 1,
  83. * "pageSize": 10
  84. * }
  85. * }
  86. * }
  87. *
  88. * @apiErrorExample {json} Error-Response:
  89. * HTTP/1.1 500 Internal Server Error
  90. * {
  91. * "status": false,
  92. * "message": "失败",
  93. * "errors": ["错误信息"]
  94. * }
  95. */
  96. router.get('/', async function(req, res, next) {
  97. try {
  98. const query = req.query
  99. //当前是第几页,如果不传,那就是第一页
  100. const currentPage = Math.abs(Number(query.currentPage)) || 1
  101. //每页显示多少条数据,如果不传,那就显示10条
  102. const pageSize = Math.abs(Number(query.pageSize)) || 10
  103. //计算 offset
  104. const offset = (currentPage - 1) * pageSize
  105. const condition = {
  106. order:[['id','DESC']],
  107. limit:pageSize,
  108. offset,
  109. include: [{
  110. model: Category,
  111. as: 'cropInfo',
  112. attributes: ['id', 'name', 'level', 'parentId'],
  113. required: false // LEFT JOIN,即使没有作物也能返回文章
  114. }]
  115. }
  116. // 构建查询条件
  117. const whereConditions = {};
  118. // 标题搜索
  119. if(query.title){
  120. whereConditions.title = {
  121. [Op.like]:`%${query.title}%`
  122. }
  123. }
  124. // 作物筛选 - 支持多选和包含子分类
  125. if(query.cropIds){
  126. let cropIds = [];
  127. // 处理cropIds参数(支持逗号分隔的多个ID)
  128. if(typeof query.cropIds === 'string'){
  129. cropIds = query.cropIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
  130. } else if(Array.isArray(query.cropIds)){
  131. cropIds = query.cropIds.map(id => parseInt(id)).filter(id => !isNaN(id));
  132. } else {
  133. cropIds = [parseInt(query.cropIds)].filter(id => !isNaN(id));
  134. }
  135. if(cropIds.length > 0){
  136. // 获取所有选中的分类及其子分类的ID
  137. const allCropIds = await getAllCategoryIdsWithChildren(cropIds);
  138. whereConditions.crop = {
  139. [Op.in]: allCropIds
  140. };
  141. }
  142. }
  143. // 用户分类筛选 - 根据用户传递的category参数值查询
  144. if(query.categoryId){
  145. const categoryId = parseInt(query.categoryId);
  146. if(!isNaN(categoryId)){
  147. whereConditions.category = categoryId;
  148. }
  149. }
  150. // 推荐筛选 - 根据是否推荐进行筛选
  151. if(query.isRecommended !== undefined){
  152. const isRecommended = parseInt(query.isRecommended);
  153. if(!isNaN(isRecommended) && (isRecommended === 0 || isRecommended === 1)){
  154. whereConditions.isRecommended = isRecommended;
  155. }
  156. }
  157. // 如果有查询条件,添加到condition中
  158. if(Object.keys(whereConditions).length > 0){
  159. condition.where = whereConditions;
  160. }
  161. const {count ,rows} = await Article.findAndCountAll(condition)
  162. res.json({
  163. status:true,
  164. message:'成功',
  165. data:{
  166. articles:rows,
  167. pagination:{
  168. total:count,
  169. currentPage,
  170. pageSize
  171. }
  172. }
  173. });
  174. }catch(error){
  175. res.status(500).json({
  176. status:false,
  177. message:'失败',
  178. errors:[error.message]
  179. });
  180. }
  181. });
  182. /**
  183. * @api {get} /admin/articles/:id 查询文章详情
  184. * @apiName GetArticleById
  185. * @apiGroup Articles
  186. * @apiVersion 1.0.0
  187. *
  188. * @apiDescription 根据文章ID获取文章详细信息
  189. *
  190. * @apiParam {Number} id 文章ID(路径参数)
  191. *
  192. * @apiSuccess {Boolean} status 请求状态
  193. * @apiSuccess {String} message 响应消息
  194. * @apiSuccess {Object} data 文章详细信息
  195. * @apiSuccess {Number} data.id 文章ID
  196. * @apiSuccess {String} data.title 文章标题
  197. * @apiSuccess {String} [data.subtitle] 文章副标题
  198. * @apiSuccess {String} data.content 文章内容
  199. * @apiSuccess {Number} data.type 文章类型
  200. * @apiSuccess {String} [data.img] 文章图片
  201. * @apiSuccess {Date} [data.date] 文章日期
  202. * @apiSuccess {String} [data.author] 作者
  203. * @apiSuccess {Number} data.category 用户分类ID
  204. * @apiSuccess {Number} data.crop 作物分类ID
  205. * @apiSuccess {Number} data.isRecommended 是否推荐(0-不推荐,1-推荐)
  206. * @apiSuccess {String} [data.seoKeyword] SEO关键词
  207. * @apiSuccess {String} [data.seoDescription] SEO描述
  208. * @apiSuccess {Date} data.createdAt 创建时间
  209. * @apiSuccess {Date} data.updatedAt 更新时间
  210. * @apiSuccess {Object} [data.cropInfo] 作物信息
  211. * @apiSuccess {Number} data.cropInfo.id 作物ID
  212. * @apiSuccess {String} data.cropInfo.name 作物名称
  213. * @apiSuccess {Number} data.cropInfo.level 作物层级
  214. * @apiSuccess {Number} data.cropInfo.parentId 父级作物ID
  215. *
  216. * @apiSuccessExample {json} Success-Response:
  217. * HTTP/1.1 200 OK
  218. * {
  219. * "status": true,
  220. * "message": "成功",
  221. * "data": {
  222. * "id": 96,
  223. * "title": "测试文章",
  224. * "subtitle": "副标题",
  225. * "content": "<p>文章内容</p>",
  226. * "type": 1,
  227. * "img": null,
  228. * "date": null,
  229. * "author": "作者",
  230. * "category": 1,
  231. * "crop": 43,
  232. * "isRecommended": 1,
  233. * "seoKeyword": null,
  234. * "seoDescription": null,
  235. * "createdAt": "2025-09-14T09:21:24.000Z",
  236. * "updatedAt": "2025-09-14T09:21:24.000Z",
  237. * "cropInfo": {
  238. * "id": 43,
  239. * "name": "荔枝",
  240. * "level": 2,
  241. * "parentId": 40
  242. * }
  243. * }
  244. * }
  245. *
  246. * @apiErrorExample {json} Error-Response:
  247. * HTTP/1.1 404 Not Found
  248. * {
  249. * "status": false,
  250. * "message": "文章未找到"
  251. * }
  252. */
  253. router.get('/:id', async function(req, res, next) {
  254. try {
  255. //获取文章id
  256. const {id} = req.params
  257. //查询文章
  258. const article = await Article.findByPk(id, {
  259. include: [{
  260. model: Category,
  261. as: 'cropInfo',
  262. attributes: ['id', 'name', 'level', 'parentId'],
  263. required: false
  264. }]
  265. })
  266. if(article){
  267. res.json({
  268. status:true,
  269. message:'成功',
  270. data:article
  271. });
  272. }else{
  273. res.status(404).json({
  274. status:false,
  275. message:'文章未找到',
  276. });
  277. }
  278. }catch(error){
  279. res.status(500).json({
  280. status:false,
  281. message:'失败',
  282. errors:[error.message]
  283. });
  284. }
  285. });
  286. /**
  287. * @api {post} /admin/articles 创建文章
  288. * @apiName CreateArticle
  289. * @apiGroup Articles
  290. * @apiVersion 1.0.0
  291. *
  292. * @apiDescription 创建新的文章,支持富文本内容和图片
  293. *
  294. * @apiParam {String} title 文章标题(必填,1-500字符)
  295. * @apiParam {String} content 文章内容(必填,富文本格式,最大5MB)
  296. * @apiParam {Number} [type] 文章类型
  297. * @apiParam {String} [img] 文章图片URL
  298. * @apiParam {Date} [date] 文章发布日期
  299. * @apiParam {String} [author] 作者
  300. * @apiParam {Number} [category] 用户分类ID(用户传递的参数)
  301. * @apiParam {Number} [crop] 作物分类ID
  302. * @apiParam {Number} [isRecommended=0] 是否推荐,0-不推荐,1-推荐
  303. * @apiParam {String} [subtitle] 副标题(最大200字符)
  304. * @apiParam {String} [seoKeyword] SEO关键词
  305. * @apiParam {String} [seoDescription] SEO描述
  306. *
  307. * @apiSuccess {Boolean} status 请求状态
  308. * @apiSuccess {String} message 响应消息
  309. * @apiSuccess {Object} data 创建的文章信息
  310. * @apiSuccess {Number} data.id 文章ID
  311. * @apiSuccess {String} data.title 文章标题
  312. * @apiSuccess {String} [data.subtitle] 文章副标题
  313. * @apiSuccess {String} data.content 文章内容
  314. * @apiSuccess {Number} data.type 文章类型
  315. * @apiSuccess {String} [data.img] 文章图片
  316. * @apiSuccess {Date} [data.date] 文章日期
  317. * @apiSuccess {String} [data.author] 作者
  318. * @apiSuccess {Number} data.category 用户分类ID
  319. * @apiSuccess {Number} data.crop 作物分类ID
  320. * @apiSuccess {Number} data.isRecommended 是否推荐
  321. * @apiSuccess {String} [data.seoKeyword] SEO关键词
  322. * @apiSuccess {String} [data.seoDescription] SEO描述
  323. * @apiSuccess {Date} data.createdAt 创建时间
  324. * @apiSuccess {Date} data.updatedAt 更新时间
  325. *
  326. * @apiSuccessExample {json} Success-Response:
  327. * HTTP/1.1 201 Created
  328. * {
  329. * "status": true,
  330. * "message": "成功",
  331. * "data": {
  332. * "id": 97,
  333. * "title": "新文章标题",
  334. * "subtitle": "副标题",
  335. * "content": "<p>文章内容</p>",
  336. * "type": 1,
  337. * "img": null,
  338. * "date": null,
  339. * "author": "作者",
  340. * "category": 1,
  341. * "crop": 43,
  342. * "isRecommended": 1,
  343. * "seoKeyword": null,
  344. * "seoDescription": null,
  345. * "createdAt": "2025-09-14T09:21:49.333Z",
  346. * "updatedAt": "2025-09-14T09:21:49.333Z"
  347. * }
  348. * }
  349. *
  350. * @apiErrorExample {json} Error-Response:
  351. * HTTP/1.1 400 Bad Request
  352. * {
  353. * "status": false,
  354. * "message": "请求参数错误",
  355. * "errors": ["标题不能为空"]
  356. * }
  357. *
  358. * @apiErrorExample {json} Error-Response:
  359. * HTTP/1.1 400 Bad Request
  360. * {
  361. * "status": false,
  362. * "message": "请求参数错误",
  363. * "errors": ["推荐字段只能是0或1"]
  364. * }
  365. *
  366. * @apiErrorExample {json} Error-Response:
  367. * HTTP/1.1 400 Bad Request
  368. * {
  369. * "status": false,
  370. * "message": "请求参数错误",
  371. * "errors": ["副标题长度不能超过200个字符"]
  372. * }
  373. */
  374. router.post('/', async function(req, res, next) {
  375. try {
  376. // 添加请求日志
  377. console.log('=== 创建文章请求开始 ===');
  378. console.log('请求体大小:', JSON.stringify(req.body).length);
  379. console.log('Content字段长度:', req.body.content ? req.body.content.length : 0);
  380. console.log('Title字段长度:', req.body.title ? req.body.title.length : 0);
  381. //白名单过滤
  382. const body = filterBody(req)
  383. console.log('过滤后的数据:', {
  384. titleLength: body.title ? body.title.length : 0,
  385. contentLength: body.content ? body.content.length : 0,
  386. hasImage: !!body.img,
  387. type: body.type
  388. });
  389. const article = await Article.create(body)
  390. console.log('文章创建成功, ID:', article.id);
  391. console.log('=== 创建文章请求结束 ===');
  392. res.status(201).json({
  393. status:true,
  394. message:'成功',
  395. data:article
  396. });
  397. }catch(error){
  398. // 添加详细的错误日志
  399. console.error('=== 创建文章错误 ===');
  400. console.error('错误名称:', error.name);
  401. console.error('错误消息:', error.message);
  402. console.error('错误堆栈:', error.stack);
  403. console.error('请求体大小:', JSON.stringify(req.body).length);
  404. console.error('请求体:', JSON.stringify(req.body, null, 2));
  405. if(error.message === '标题不能为空' || error.message === '内容不能为空' ||
  406. error.message.includes('长度不能超过') || error.message.includes('不允许的脚本标签') ||
  407. error.message.includes('推荐字段只能是0或1') || error.message.includes('副标题长度不能超过')){
  408. res.status(400).json({
  409. status:false,
  410. message:'请求参数错误',
  411. errors:[error.message]
  412. });
  413. }else if(error.name === 'SequelizeValidationError'){
  414. const errors = error.errors.map(e => e.message)
  415. res.status(400).json({
  416. status:false,
  417. message:'数据验证失败',
  418. errors
  419. });
  420. }else if(error.name === 'SequelizeDatabaseError'){
  421. console.error('数据库错误详情:', error.original);
  422. res.status(500).json({
  423. status:false,
  424. message:'数据库错误',
  425. errors:['数据库操作失败,请稍后重试']
  426. });
  427. }else if(error.name === 'SequelizeConnectionError'){
  428. res.status(500).json({
  429. status:false,
  430. message:'数据库连接错误',
  431. errors:['数据库连接失败,请稍后重试']
  432. });
  433. }else{
  434. res.status(500).json({
  435. status:false,
  436. message:'服务器内部错误',
  437. errors:['服务器处理请求时发生错误,请稍后重试']
  438. });
  439. }
  440. }
  441. });
  442. /**
  443. * @api {delete} /admin/articles/:id 删除文章
  444. * @apiName DeleteArticle
  445. * @apiGroup Articles
  446. * @apiVersion 1.0.0
  447. *
  448. * @apiDescription 根据文章ID删除文章
  449. *
  450. * @apiParam {Number} id 文章ID(路径参数)
  451. *
  452. * @apiSuccess {Boolean} status 请求状态
  453. * @apiSuccess {String} message 响应消息
  454. *
  455. * @apiSuccessExample {json} Success-Response:
  456. * HTTP/1.1 200 OK
  457. * {
  458. * "status": true,
  459. * "message": "成功"
  460. * }
  461. *
  462. * @apiErrorExample {json} Error-Response:
  463. * HTTP/1.1 404 Not Found
  464. * {
  465. * "status": false,
  466. * "message": "文章未找到"
  467. * }
  468. */
  469. router.delete('/:id', async function(req, res, next) {
  470. try {
  471. //获取文章id
  472. const {id} = req.params
  473. //查询文章
  474. const article = await Article.findByPk(id)
  475. if(article){
  476. await article.destroy()
  477. res.json({
  478. status:true,
  479. message:'成功',
  480. });
  481. }else{
  482. res.status(404).json({
  483. status:false,
  484. message:'文章未找到',
  485. });
  486. }
  487. }catch(error){
  488. res.status(500).json({
  489. status:false,
  490. message:'失败',
  491. errors:[error.message]
  492. });
  493. }
  494. });
  495. /**
  496. * @api {put} /admin/articles/:id 更新文章
  497. * @apiName UpdateArticle
  498. * @apiGroup Articles
  499. * @apiVersion 1.0.0
  500. *
  501. * @apiDescription 根据文章ID更新文章信息
  502. *
  503. * @apiParam {Number} id 文章ID(路径参数)
  504. * @apiParam {String} [title] 文章标题(1-500字符)
  505. * @apiParam {String} [content] 文章内容(富文本格式,最大5MB)
  506. * @apiParam {Number} [type] 文章类型
  507. * @apiParam {String} [img] 文章图片URL
  508. * @apiParam {Date} [date] 文章发布日期
  509. * @apiParam {String} [author] 作者
  510. * @apiParam {Number} [category] 用户分类ID
  511. * @apiParam {Number} [crop] 作物分类ID
  512. * @apiParam {Number} [isRecommended] 是否推荐,0-不推荐,1-推荐
  513. * @apiParam {String} [subtitle] 副标题(最大200字符)
  514. * @apiParam {String} [seoKeyword] SEO关键词
  515. * @apiParam {String} [seoDescription] SEO描述
  516. *
  517. * @apiSuccess {Boolean} status 请求状态
  518. * @apiSuccess {String} message 响应消息
  519. * @apiSuccess {Object} data 更新后的文章信息
  520. *
  521. * @apiSuccessExample {json} Success-Response:
  522. * HTTP/1.1 200 OK
  523. * {
  524. * "status": true,
  525. * "message": "成功",
  526. * "data": {
  527. * "id": 97,
  528. * "title": "更新后的标题",
  529. * "subtitle": "更新后的副标题",
  530. * "content": "<p>更新后的内容</p>",
  531. * "type": 1,
  532. * "img": null,
  533. * "date": null,
  534. * "author": "作者",
  535. * "category": 1,
  536. * "crop": 43,
  537. * "isRecommended": 1,
  538. * "seoKeyword": null,
  539. * "seoDescription": null,
  540. * "createdAt": "2025-09-14T09:21:49.333Z",
  541. * "updatedAt": "2025-09-14T09:22:10.000Z"
  542. * }
  543. * }
  544. *
  545. * @apiErrorExample {json} Error-Response:
  546. * HTTP/1.1 404 Not Found
  547. * {
  548. * "status": false,
  549. * "message": "文章未找到"
  550. * }
  551. *
  552. * @apiErrorExample {json} Error-Response:
  553. * HTTP/1.1 400 Bad Request
  554. * {
  555. * "status": false,
  556. * "message": "请求参数错误",
  557. * "errors": ["推荐字段只能是0或1"]
  558. * }
  559. */
  560. router.put('/:id', async function(req, res, next) {
  561. try {
  562. //获取文章id
  563. const {id} = req.params
  564. //查询文章
  565. const article = await Article.findByPk(id)
  566. //白名单过滤
  567. const body = filterBody(req)
  568. if(article){
  569. await article.update(body)
  570. res.json({
  571. status:true,
  572. message:'成功',
  573. data:article
  574. });
  575. }else{
  576. res.status(404).json({
  577. status:false,
  578. message:'文章未找到',
  579. });
  580. }
  581. }catch(error){
  582. res.status(500).json({
  583. status:false,
  584. message:'失败',
  585. errors:[error.message]
  586. });
  587. }
  588. });
  589. /**
  590. * 获取分类及其所有子分类的ID列表
  591. * @param {Array} categoryIds - 分类ID数组
  592. * @returns {Promise<Array>} 包含所有分类ID的数组
  593. */
  594. async function getAllCategoryIdsWithChildren(categoryIds) {
  595. try {
  596. let allIds = [...categoryIds];
  597. // 递归获取所有子分类
  598. async function getChildrenIds(parentIds) {
  599. if (parentIds.length === 0) return [];
  600. const children = await Category.findAll({
  601. where: {
  602. parentId: {
  603. [Op.in]: parentIds
  604. }
  605. },
  606. attributes: ['id']
  607. });
  608. const childrenIds = children.map(child => child.id);
  609. if (childrenIds.length > 0) {
  610. allIds = allIds.concat(childrenIds);
  611. // 递归获取子分类的子分类
  612. const grandChildrenIds = await getChildrenIds(childrenIds);
  613. allIds = allIds.concat(grandChildrenIds);
  614. }
  615. return childrenIds;
  616. }
  617. await getChildrenIds(categoryIds);
  618. // 去重并返回
  619. return [...new Set(allIds)];
  620. } catch (error) {
  621. console.error('获取分类ID列表错误:', error);
  622. // 如果出错,返回原始ID列表
  623. return categoryIds;
  624. }
  625. }
  626. function filterBody(req){
  627. try {
  628. // 数据清理和验证
  629. const body = {
  630. title: req.body.title ? String(req.body.title).trim() : null,
  631. content: req.body.content ? String(req.body.content) : null,
  632. type: req.body.type ? parseInt(req.body.type) : null,
  633. img: req.body.img ? String(req.body.img).trim() : null,
  634. date: req.body.date ? new Date(req.body.date) : null,
  635. author: req.body.author ? String(req.body.author).trim() : null,
  636. category: req.body.category ? parseInt(req.body.category) : null,
  637. crop: req.body.crop ? parseInt(req.body.crop) : null,
  638. isRecommended: req.body.isRecommended !== undefined ? parseInt(req.body.isRecommended) : 0,
  639. subtitle: req.body.subtitle ? String(req.body.subtitle).trim() : null,
  640. seoKeyword: req.body.seoKeyword ? String(req.body.seoKeyword).trim() : null,
  641. seoDescription: req.body.seoDescription ? String(req.body.seoDescription).trim() : null
  642. };
  643. // 验证必填字段
  644. if (!body.title) {
  645. throw new Error('标题不能为空');
  646. }
  647. if (!body.content) {
  648. throw new Error('内容不能为空');
  649. }
  650. // 验证标题长度 - 放宽限制以适应富文本编辑器
  651. if (body.title.length > 500) {
  652. throw new Error('标题长度不能超过500个字符');
  653. }
  654. // 验证内容长度 - 防止过大的内容
  655. if (body.content.length > 5000000) { // 5MB限制
  656. throw new Error('内容过长,请减少内容长度');
  657. }
  658. // 验证推荐字段 - 只能是0或1
  659. if (body.isRecommended !== 0 && body.isRecommended !== 1) {
  660. throw new Error('推荐字段只能是0或1');
  661. }
  662. // 验证副标题长度
  663. if (body.subtitle && body.subtitle.length > 200) {
  664. throw new Error('副标题长度不能超过200个字符');
  665. }
  666. // 检查富文本内容是否包含危险标签或脚本
  667. const dangerousTags = /<script[^>]*>.*?<\/script>/gi;
  668. if (dangerousTags.test(body.content)) {
  669. throw new Error('内容包含不允许的脚本标签');
  670. }
  671. return body;
  672. } catch (error) {
  673. console.error('filterBody错误:', error);
  674. throw error;
  675. }
  676. }
  677. module.exports = router;