【Nest教程】實現一個簡單的用戶增刪改查功能

鏈接MySQL,實現一個簡單的增刪改查功能html

前面幾章咱們講了項目的初始,鏈接MySQL,這章咱們主要實現增刪改查接口,在src下新建user文件夾,咱們的全部功能都寫在這個文件夾下。數據庫

1 新建entityasync

項目開始配置鏈接數據庫的時候,咱們 synchronize 選擇的事true,即便咱們庫裏沒有表,經過entity也能夠自動生成表ide

import { Column, Entity, PrimaryGeneratedColumn, BaseEntity } from 'typeorm';

/**
 * 列選項參考
 * https://typeorm.biunav.com/zh/entities.html#%E5%88%97%E9%80%89%E9%A1%B9
 **/
@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', name: 'name', comment: '用戶名' })
  name: string;

  @Column({ type: 'varchar', name: 'nickname', comment: '暱稱' })
  nickname: string;

  @Column({ type: 'varchar', name: 'password', comment: '密碼' })
  password: string;

  @Column({ type: 'varchar', length: 11, name: 'mobile', comment: '手機號' })
  mobile: string;

  @Column({ type: 'varchar', nullable: true, name: 'avatar', comment: '頭像' })
  avatar: string;

  @Column({ type: 'varchar', default: '未知', name: 'gender', comment: '性別' })
  gender: string;

  @Column({
    type: 'varchar',
    default: '普通會員',
    name: 'user_level',
    comment: '用戶級別',
  })
  userLevel: string;

  @Column({
    type: 'varchar',
    nullable: true,
    name: 'province',
    comment: '省份',
  })
  province: string;

  @Column({ type: 'varchar', nullable: true, name: 'city', comment: '城市' })
  city: string;

  @Column({ type: 'datetime', nullable: true, name: 'create_time' })
  createTime: number;

  @Column({ type: 'datetime', nullable: true, name: 'update_time' })
  updateTime: number;
}

上面的內容定義的是表的字段及字段類型等post

2 新建controllerui

這裏定義了四個路由,所有爲post請求方式this

import { ApiTags, ApiParam, ApiQuery, ApiHeader } from '@nestjs/swagger';
import { Controller, Get, Post, Body, Logger } from '@nestjs/common';
import { UserService } from './user.service';
import { QueryUserDto } from './Dto/queryUser.dto';
import { AddUserDto } from './Dto/addUser.dto';
import { UpdateUserDto } from './Dto/updateUser.dto';
import { DeleteUserDto } from './Dto/deleteUser.dto';

/**
 *
 * @author lidonghui
 * @version 1
 * @date 2021/01/18 09:57
 */
@ApiTags('用戶管理')
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  /**
   * 用戶管理-分頁查詢
   */
  @ApiQuery({
    name: 'name',
    description: '用戶名',
  })
  @Post('/page')
  findAll(@Body() queryUserDto: QueryUserDto): Promise<{}> {
    Logger.log(`分頁查詢接收參數:${JSON.stringify(queryUserDto)}`);
    return this.userService.pageQuery(queryUserDto);
  }

  /**
   * 用戶管理-增長用戶
   */
  @Post('/add')
  addUser(@Body() addUserDto: AddUserDto): Promise<boolean> {
    Logger.log(`增長用戶接收參數:${JSON.stringify(addUserDto)}`);
    return this.userService.save(addUserDto);
  }

  /**
   * 用戶管理-編輯用戶
   */
  @Post('/edit')
  updateUser(@Body() updateUserDto: UpdateUserDto): Promise<boolean> {
    Logger.log(`編輯用戶接收參數:${JSON.stringify(updateUserDto)}`);
    return this.userService.save(updateUserDto);
  }

  /**
   * 用戶管理-刪除用戶
   */
  @Post('/delete')
  deleteUser(@Body() deleteUserDto: DeleteUserDto): Promise<boolean> {
    Logger.log(`刪除用戶接收參數:${JSON.stringify(deleteUserDto)}`);
    return this.userService.delete(deleteUserDto);
  }
}

3 新建servicecode

這裏主要的實現是對庫的操做,這裏面就包含了增刪改查orm

import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly UserRepository: Repository<User>,
  ) {}

  private readonly User: User[] = [];

  // 分頁查詢
  async pageQuery(parameter: any): Promise<any> {
    Logger.log(`請求參數:${JSON.stringify(parameter)}`);

    // 定義返回格式
    let result = {
      pageNo: Number(parameter.pageNo),
      pageSize: Number(parameter.pageSize),
      totalPage: 0,
      totalRows: 0,
      rows: [],
    };

    // 返回條數
    let SQLwhere: any = {};
    if (parameter.name != undefined) {
      SQLwhere.name = parameter.name;
    }
    result.rows = await this.UserRepository.find({
      where: SQLwhere,
      order: {
        id: 'DESC',
      },
      skip: (parameter.pageNo - 1) * Number(parameter.pageSize), // 分頁,跳過幾項
      take: parameter.pageSize, // 分頁,取幾項
      cache: true,
    });

    // 總條數
    result.totalRows = await this.UserRepository.count();

    // 總頁數
    result.totalPage = Math.ceil(
      (await this.UserRepository.count()) / parameter.pageSize,
    );

    return result;
  }

  // 增長/更新
  async save(parameter: any): Promise<boolean> {
    Logger.log(`請求參數:${JSON.stringify(parameter)}`);
    try {
      let a = await this.UserRepository.save(parameter);
      return true;
    } catch (error) {
      Logger.log(`請求失敗:${JSON.stringify(error)}`);
      return false;
    }
  }

  // 刪除
  async delete(ids: any): Promise<boolean> {
    Logger.log(`請求參數:${JSON.stringify(ids)}`);
    try {
      let a = await this.UserRepository.delete(ids.id);
      Logger.log(`刪除返回數據:${JSON.stringify(a)}`);
      if (a.affected == 0) {
        return false;
      } else {
        return true;
      }
    } catch (error) {
      return false;
    }
  }
}

4 新建modulehtm

import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';

import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UserService],
  controllers: [UserController],
})
export class UserModule {}

5 新建Dto

Dto文件夾有四個文件,分別爲addUser.dto.ts、deleteUser.dto.ts、queryUser.dto.ts和updateUser.dto.ts,這四個是查詢及驗證使用

1 addUser.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty } from 'class-validator';
export class AddUserDto {
  @ApiProperty()
  @IsNotEmpty({ message: '用戶名不爲空' })
  readonly name: string;

  @ApiProperty()
  @IsNotEmpty({ message: '暱稱不爲空' })
  readonly nickname: string;

  @ApiProperty()
  @IsNotEmpty({ message: '密碼不爲空' })
  readonly password: string;

  @ApiProperty()
  @IsNotEmpty({ message: '手機號不爲空' })
  readonly mobile: string;

  @ApiProperty()
  readonly avatar: string;

  @ApiProperty()
  readonly gender: string;

  @ApiProperty()
  readonly userLevel: string;

  @ApiProperty()
  readonly province: string;

  @ApiProperty()
  readonly city: string;
}
2 deleteUser.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsInt } from 'class-validator';
export class DeleteUserDto {
  @ApiProperty()
  @IsInt({ message: 'id應爲數字' })
  @IsNotEmpty({ message: 'id不爲空' })
  readonly id: number;
}
3 queryUser.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, Min, IsInt } from 'class-validator';
export class QueryUserDto {
  @ApiProperty()
  readonly name: string;

  @ApiProperty()
  @Min(1, { message: '分頁不能小於1' })
  @IsInt({ message: '分頁應爲數字' })
  @IsNotEmpty({ message: '分頁不能爲空' })
  readonly pageNo: number;

  @ApiProperty()
  @Min(1, { message: '分頁條數不能小於1' })
  @IsInt({ message: '分頁條數應爲數字' })
  @IsNotEmpty({ message: '分頁條數不能爲空' })
  readonly pageSize: number;
}
4 updateUser.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsInt } from 'class-validator';
export class UpdateUserDto {
  @ApiProperty()
  @IsInt({ message: 'id應爲數字' })
  @IsNotEmpty({ message: 'id不爲空' })
  readonly id: number;

  @ApiProperty()
  readonly name: string;

  @ApiProperty()
  readonly nickname: string;

  @ApiProperty()
  readonly password: string;

  @ApiProperty()
  readonly mobile: string;

  @ApiProperty()
  readonly avatar: string;

  @ApiProperty()
  readonly gender: string;

  @ApiProperty()
  readonly userLevel: string;

  @ApiProperty()
  readonly province: string;

  @ApiProperty()
  readonly city: string;
}

6 運行項目

上面的是所有的配置,主要由於是此項目沒有開源,因此代碼所有複製,基本能運行。最後結果

【Nest教程】實現一個簡單的用戶增刪改查功能

相關文章
相關標籤/搜索