定义 PaginationExtension

// pagination.extension.ts
import { Prisma } from '@prisma/client';
import { pagination } from 'prisma-extension-pagination';
 
export const paginationExtension = Prisma.defineExtension(
  pagination({
    pages: {
      limit: 10, // 默认每页显示 10 条数据
      includePageCount: true,
    },
  }),
);
 

创建一个集成了Pagination 的Prisma Client

// estended-client.ts
import { PrismaClient } from '@prisma/client';
import { paginationExtension } from './extensions/pagination.extension';
 
function extendClient(base: PrismaClient) {
  // Add as many as you'd like - no ugly types required!
  // return base.$extends(existsExtension).$extends(findManyAndCountExtension);
  return base.$extends(paginationExtension);
}
 
class UntypedExtendedClient extends PrismaClient {
  constructor(options?: ConstructorParameters<typeof PrismaClient>[0]) {
    super(options);
 
    return extendClient(this) as this;
  }
}
 
const ExtendedPrismaClient = UntypedExtendedClient as unknown as new (
  options?: ConstructorParameters<typeof PrismaClient>[0],
) => ReturnType<typeof extendClient>;
 
export { ExtendedPrismaClient };

Prisma Svervice 继承 ExtendedPrismaClient

// prisma.service.ts
import { Injectable, OnModuleInit } from '@nestjs/common';
 
import { ExtendedPrismaClient } from './extended-client';
 
@Injectable()
export class PrismaService extends ExtendedPrismaClient implements OnModuleInit
{
  constructor() {
    super({
      log: [
        {
          emit: 'stdout',
          level: 'query',
        },
      ],
    });
  }
 
  async onModuleInit() {
    await this.$connect();
  }
}
 

Prisma Module

import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
 
@Global()
@Module({
  providers: [PrismaService],
  exports: [PrismaService],
})
export class PrismaModule {}
 
 
// main.ts
@Module({
  imports: [
    PrismaModule,
  ],
})
export class AppModule {}