Skip to content

Commit

Permalink
perf: use count() for song.info
Browse files Browse the repository at this point in the history
Signed-off-by: ZTL-UwU <zhangtianli2006@163.com>
  • Loading branch information
ZTL-UwU committed Oct 1, 2024
1 parent 846a425 commit 4ba5b9b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
4 changes: 2 additions & 2 deletions pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const { data: arrangementList } = await $api.arrangement.listSafe.useQuery();
const songListInfo = ref(0);
const timeCanSubmit = ref(true);
try {
songListInfo.value = await $api.song.info.query();
songListInfo.value = await $api.song.info.query({ getAll: false });
timeCanSubmit.value = await $api.time.currently.query();
} catch (err) {
useErrorHandler(err);
Expand Down Expand Up @@ -132,7 +132,7 @@ async function refreshData() {
if (timeCanSubmit.value) {
try {
const res = await Promise.all([
$api.song.info.query(),
$api.song.info.query({ getAll: false }),
$api.time.currently.query(),
$api.song.listSafe.query(),
]);
Expand Down
15 changes: 14 additions & 1 deletion server/trpc/controllers/song.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { LibsqlError } from '@libsql/client';
import { and, desc, eq, gt, inArray, or } from 'drizzle-orm';
import { and, count, desc, eq, gt, inArray, or } from 'drizzle-orm';
import { type TNewSong, db } from '../../db/db';
import { songs } from '~/server/db/schema';
import type { TStatus } from '~/types';
Expand Down Expand Up @@ -90,4 +90,17 @@ export class SongController {
return { success: false, message: '服务器内部错误' };
}
}

async count(getAll: boolean) {
try {
let res = 0;
if (getAll)
res = (await db.select({ count: count() }).from(songs))[0]?.count;
else
res = (await db.select({ count: count() }).from(songs).where(gt(songs.createdAt, new Date(Date.now() - 4 * 24 * 60 * 60 * 1000))))[0]?.count;
return { success: true, res, message: '获取成功' };
} catch {
return { success: false, message: '服务器内部错误' };
}
}
}
9 changes: 6 additions & 3 deletions server/trpc/routers/song.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,13 @@ export const songRouter = router({
}),

info: publicProcedure
.query(async ({ ctx }) => {
const res = await ctx.songController.getList();
.input(z.object({
getAll: z.boolean(),
}))
.query(async ({ ctx, input }) => {
const res = await ctx.songController.count(input.getAll);
if (!res.success || !res.res)
throw new TRPCError({ code: 'BAD_REQUEST', message: res.message });
else return res.res.length;
else return res.res;
}),
});

0 comments on commit 4ba5b9b

Please sign in to comment.