byChannelName.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // 1. 从pr_cms_channel表中通过name查询channel_id
  17. const channel = await DB.table('pr_cms_channel')
  18. .where('name', channelName)
  19. .where('status', 'normal')
  20. .select('id')
  21. .first();
  22. // 如果没有找到对应的频道,返回空数组
  23. if (!channel)
  24. return createSuccessResponse(new CommonPageResult<IArticle>(undefined, [], page, pageSize, 0));
  25. const subChannelIds = (await DB.table('pr_cms_channel')
  26. .where('parent_id', channel.id)
  27. .where('status', 'normal')
  28. .select('id')
  29. .get()).map(item => item.id);
  30. // 2. 从pr_cms_archives表中通过channel_id查询文章
  31. const articles = await DB.table('pr_cms_archives')
  32. .whereIn('channel_id', [channel.id, ...subChannelIds])
  33. .where('status', 'normal')
  34. .whereNull('deletetime')
  35. .orderBy('weigh', 'desc')
  36. .orderBy('publishtime', 'desc')
  37. .orderBy('createtime', 'desc')
  38. .orderBy('id', 'asc')
  39. .paginate(page, pageSize);
  40. if (!articles)
  41. return createErrorResponse('文章不存在');
  42. return createSuccessResponse({
  43. channel_id: channel.id,
  44. ...articles
  45. });
  46. } catch (error) {
  47. return createErrorResponse(error);
  48. }
  49. });