byChannelName.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 onlySelf = query.onlySelf === 'true';
  14. const bannedChannels = (query.bannedChannels as string || '').split(',');
  15. const channelName = query.channelName as string;
  16. if (!channelName)
  17. return createErrorResponse('分类名称不能为空');
  18. const channelNames = channelName.split(',');
  19. // 1. 从pr_cms_channel表中通过name查询channel_id
  20. const channelIds : number[] = [];
  21. for (const channelName of channelNames) {
  22. const channel = await DB.table('pr_cms_channel')
  23. .where('name', channelName)
  24. .where('status', 'normal')
  25. .select('id')
  26. .first();
  27. if (channel) {
  28. channelIds.push(channel.id);
  29. if (!onlySelf) {
  30. const subChannels = (await DB.table('pr_cms_channel')
  31. .where('parent_id', channel.id)
  32. .where('status', 'normal')
  33. .select('id', '')
  34. .get()).map(item => item.id);
  35. if (bannedChannels.length > 0) {
  36. channelIds.push(...subChannels.filter(item => !bannedChannels.includes(item.name)).map(item => item.id));
  37. } else
  38. channelIds.push(...subChannels.map(item => item.id));
  39. }
  40. }
  41. }
  42. // 如果没有找到对应的频道,返回空数组
  43. if (channelIds.length === 0)
  44. return createSuccessResponse(new CommonPageResult<IArticle>(undefined, [], page, pageSize, 0));
  45. // 2. 从pr_cms_archives表中通过channel_id查询文章
  46. const articles = await DB.table('pr_cms_archives')
  47. .whereIn('channel_id', channelIds)
  48. .where('status', 'normal')
  49. .whereNull('deletetime')
  50. .orderBy('weigh', 'desc')
  51. .orderBy('publishtime', 'desc')
  52. .orderBy('createtime', 'desc')
  53. .orderBy('id', 'asc')
  54. .paginate(page, pageSize);
  55. if (!articles)
  56. return createErrorResponse('文章不存在');
  57. return createSuccessResponse({
  58. channel_id: channelIds[0],
  59. ...articles
  60. });
  61. } catch (error) {
  62. return createErrorResponse(error);
  63. }
  64. });