NestJS TypeORM Pagination

本文介绍了如何在NestJS项目中使用TypeORM实现数据分页。通过创建一个产品模块,设置数据库连接,并在控制器和服务层实现分页功能,展示了如何处理API的分页请求。示例使用了MySQL数据库,但TypeORM支持多种数据库。
摘要由CSDN通过智能技术生成

NestJS TypeORM Pagination - Demo

When working on an API, sometimes, we have to paginate our data in order to provide a good user experience. In this tutorial, we will be doing a NestJS TypeORM Pagination example. The example will be a products API.

Setting up a NestJS Project

> npm install -g @nestjs/cli

> nest new products-api

Adding TypeORM

If we’re doing pagination, we most probably have a lot of data. And when having a lot of data, we also most probably are storing that data inside a database. To interact with our database we will use TypeORM.

Let’s install and setup the module:

> yarn add @nestjs/typeorm typeorm mysql

I am using MySQL for this example, you can use whichever database you want, you just have to install the correct driver.

Next, let’s import the module in our root module, app.module.ts:

import {
    Module } from '@nestjs/common'
import {
    AppController } from './app.controller'
import {
    AppService } from './app.service'
import {
    TypeOrmModule } from '@nestjs/typeorm'

@Module({
   
  imports: [
    TypeOrmModule.forRoot({
   
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'products',
      entities: [],
      synchronize: true,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
   }

Creating the Products Module

For this module, we will create a small products module. In order to make thing simple, a product will have on an id, name, price, createdAt field.

import {
    Column, Entity, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class Product {
   
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column(<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值