|
| 1 | +import { and, count, desc, eq, like } from 'drizzle-orm' |
1 | 2 | import { wordsCountTable } from '~~/db/schema' |
2 | 3 |
|
3 | 4 | /** |
4 | | - * 查询所有字数统计记录 |
| 5 | + * 查询字数统计记录 |
| 6 | + * 支持分页、按月查询、ID查询 |
5 | 7 | * GET /api/words-count/list |
| 8 | + * Query: id, month, page, limit |
6 | 9 | */ |
7 | 10 | export default defineEventHandler(async (event) => { |
| 11 | + const query = getQuery(event) |
| 12 | + const { id, month, page = 1, limit = 20 } = query |
| 13 | + |
8 | 14 | try { |
| 15 | + // ID 查询单条数据 |
| 16 | + if (id) { |
| 17 | + const result = await event.context.db |
| 18 | + .select() |
| 19 | + .from(wordsCountTable) |
| 20 | + .where(eq(wordsCountTable.id, Number(id))) |
| 21 | + .get() |
| 22 | + return createSuccessResponse(result, '获取详情成功') |
| 23 | + } |
| 24 | + |
| 25 | + const pageNum = Number(page) |
| 26 | + const pageSize = Number(limit) |
| 27 | + const conditions = [] |
| 28 | + |
| 29 | + if (month) { |
| 30 | + conditions.push(like(wordsCountTable.createTime, `${month}%`)) |
| 31 | + } |
| 32 | + |
| 33 | + const whereClause = conditions.length > 0 ? and(...conditions) : undefined |
| 34 | + |
| 35 | + // 查询总数 |
| 36 | + const totalRes = await event.context.db |
| 37 | + .select({ count: count() }) |
| 38 | + .from(wordsCountTable) |
| 39 | + .where(whereClause) |
| 40 | + .get() |
| 41 | + const total = totalRes?.count || 0 |
| 42 | + |
| 43 | + // 分页查询 |
9 | 44 | const list = await event.context.db |
10 | 45 | .select() |
11 | 46 | .from(wordsCountTable) |
12 | | - return createSuccessResponse(list, '字数统计记录获取成功') |
| 47 | + .where(whereClause) |
| 48 | + .orderBy(desc(wordsCountTable.createTime)) |
| 49 | + .limit(pageSize) |
| 50 | + .offset((pageNum - 1) * pageSize) |
| 51 | + |
| 52 | + return createSuccessResponse({ |
| 53 | + list, |
| 54 | + total, |
| 55 | + page: pageNum, |
| 56 | + pageSize, |
| 57 | + }, '字数统计记录获取成功') |
13 | 58 | } |
14 | 59 | catch (error) { |
15 | 60 | return createErrorResponse(error instanceof Error ? error.message : '获取字数统计记录失败', 500) |
|
0 commit comments