diff --git a/src/services/user.ts b/src/services/user.ts index c9ee87a..724c280 100644 --- a/src/services/user.ts +++ b/src/services/user.ts @@ -64,27 +64,23 @@ export const queryUsers = async ({ limit = 10, page = 1, }: QueryUsers) => { - const whereConditions: Record = {} - if (name) { - whereConditions.name = { - contains: name, - } - } - if (role) { - whereConditions.role = role - } - - const orderByConditions: Record = {} - if (orderBy) { - orderByConditions[orderBy] = order - } - const result = await paginate({ modelName: 'User', page, pageSize: limit, - where: whereConditions, - orderBy: orderByConditions, + where: { + role, + name: name + ? { + contains: name, + } + : undefined, + }, + orderBy: orderBy + ? { + [orderBy]: order, + } + : undefined, }) return result diff --git a/src/utils/prisma.ts b/src/utils/prisma.ts index 52f8e7c..f9d9980 100644 --- a/src/utils/prisma.ts +++ b/src/utils/prisma.ts @@ -2,8 +2,7 @@ import { Prisma, PrismaClient } from '@prisma/client' export const prisma = new PrismaClient() -export type ModelNames = - (typeof Prisma.ModelName)[keyof typeof Prisma.ModelName] +export type ModelNames = Prisma.ModelName type PrismaOperations = Prisma.TypeMap['model'][ModelName]['operations'] @@ -31,6 +30,9 @@ export async function paginate({ // @ts-expect-error suppress type ModelName cannot be used to index type const db = prisma[modelName] + page = Math.max(1, Math.floor(page)) + pageSize = Math.max(1, Math.floor(pageSize)) + const skip = (page - 1) * pageSize const [totalCount, items] = await Promise.all([ @@ -46,12 +48,13 @@ export async function paginate({ }), ]) - const totalPages = Math.max(1, Math.ceil(totalCount / pageSize)) + const totalPages = totalCount > 0 ? Math.ceil(totalCount / pageSize) : 0 return { items, totalCount, page, + pageSize, totalPages, } }