Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
likui628 committed Oct 5, 2024
1 parent 86af865 commit 48ef9fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
30 changes: 13 additions & 17 deletions src/services/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,27 +64,23 @@ export const queryUsers = async ({
limit = 10,
page = 1,
}: QueryUsers) => {
const whereConditions: Record<string, unknown> = {}
if (name) {
whereConditions.name = {
contains: name,
}
}
if (role) {
whereConditions.role = role
}

const orderByConditions: Record<string, unknown> = {}
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
Expand Down
9 changes: 6 additions & 3 deletions src/utils/prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ModelName extends ModelNames> =
Prisma.TypeMap['model'][ModelName]['operations']
Expand Down Expand Up @@ -31,6 +30,9 @@ export async function paginate<ModelName extends ModelNames>({
// @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([
Expand All @@ -46,12 +48,13 @@ export async function paginate<ModelName extends ModelNames>({
}),
])

const totalPages = Math.max(1, Math.ceil(totalCount / pageSize))
const totalPages = totalCount > 0 ? Math.ceil(totalCount / pageSize) : 0

return {
items,
totalCount,
page,
pageSize,
totalPages,
}
}

0 comments on commit 48ef9fb

Please sign in to comment.