byChannelName.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { CommonPageResult, ICommonPageResult } from '~~/server/db/CommonModel';
  5. import type { IArticle } from './[id]';
  6. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<ICommonPageResult<IArticle> & {
  7. channel_id: number;
  8. }>>>(async (event) => {
  9. try {
  10. const query = getQuery(event);
  11. const page = Number(query.page as string) || 1;
  12. const pageSize = Number(query.pageSize as string) || 10;
  13. const channelName = query.channelName as string;
  14. if (!channelName)
  15. return createErrorResponse('分类名称不能为空');
  16. const channelNames = channelName.split(',');
  17. // 1. 从pr_cms_channel表中通过name查询channel_id
  18. const channelIds : number[] = [];
  19. for (const channelName of channelNames) {
  20. const channel = await DB.table('pr_cms_channel')
  21. .where('name', channelName)
  22. .where('status', 'normal')
  23. .select('id')
  24. .first();
  25. if (channel) {
  26. channelIds.push(channel.id);
  27. const subChannelIds = (await DB.table('pr_cms_channel')
  28. .where('parent_id', channel.id)
  29. .where('status', 'normal')
  30. .select('id')
  31. .get()).map(item => item.id);
  32. channelIds.push(...subChannelIds);
  33. }
  34. }
  35. // 如果没有找到对应的频道,返回空数组
  36. if (channelIds.length === 0)
  37. return createSuccessResponse(new CommonPageResult<IArticle>(undefined, [], page, pageSize, 0));
  38. // 2. 从pr_cms_archives表中通过channel_id查询文章
  39. const articles = await DB.table('pr_cms_archives')
  40. .whereIn('channel_id', channelIds)
  41. .where('status', 'normal')
  42. .whereNull('deletetime')
  43. .orderBy('weigh', 'desc')
  44. .orderBy('publishtime', 'desc')
  45. .orderBy('createtime', 'desc')
  46. .orderBy('id', 'asc')
  47. .paginate(page, pageSize);
  48. if (!articles)
  49. return createErrorResponse('文章不存在');
  50. return createSuccessResponse({
  51. channel_id: channelIds[0],
  52. ...articles
  53. });
  54. } catch (error) {
  55. return createErrorResponse(error);
  56. }
  57. });