nestjs学习(三):连接数据库实现简单增删查改
安装依赖
1
| pnpm add --save @nestjs/typeorm typeorm mysql2
|
配置数据库连接
在app.module.ts中配置数据库连接信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { UserModule } from './user/user.module'; import { TypeOrmModule } from '@nestjs/typeorm';
@Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'root', database: 'nest_demo', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, logging: true, retryDelay: 500, retryAttempts: 10, autoLoadEntities: true,
}), UserModule], controllers: [AppController], providers: [AppService], }) export class AppModule {}
|
创建实体文件
src/user/entities/user.entity.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity() export class User { @PrimaryGeneratedColumn() id: number;
@Column() username: string;
@Column() password: string;
@Column() age: number; }
|
模块文件
user.module.ts
1 2 3 4 5 6 7 8 9 10 11 12
| import { Module } from '@nestjs/common'; import { UserService } from './user.service'; import { UserController } from './user.controller'; import { TypeOrmModule } from '@nestjs/typeorm'; import { User } from './entities/user.entity';
@Module({ imports: [TypeOrmModule.forFeature([User])], controllers: [UserController], providers: [UserService], }) export class UserModule {}
|
增删查改
user.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import { User } from './entities/user.entity'; import { Injectable } from '@nestjs/common'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { hash, verify } from '../utils/md5';
@Injectable() export class UserService { constructor( @InjectRepository(User) private usersRepository: Repository<User>, ) { } async create(createUserDto: CreateUserDto) { createUserDto.password = hash(createUserDto.password, process.env.MD5_SALT) const user = await this.usersRepository.save(createUserDto) const { password, ...userWithoutPassword } = user; return userWithoutPassword }
async findAll() { return await this.usersRepository.find(); }
async findOne(id: number) { const user = await this.usersRepository.findOneBy({ id }) return user; }
async update(id: number, updateUserDto: UpdateUserDto) { const user = await this.usersRepository.update(id, updateUserDto) return user; }
async remove(id: number) { const user = await this.usersRepository.delete(id) return user; } }
|
对密码进行加密,使用crypto-js包
1
| pnpm i crypto-js @types/crypto-js
|
md5.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import { MD5 } from "crypto-js";
export function hash(val: string, salt = "") { return MD5(`${val}${salt}`).toString(); }
export function verify(val: string, hashVal: string, salt = "") { return hash(val, salt) === hashVal; }
|
user.controller.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import { Controller, Get, Post, Body, Patch, Param, Delete, HttpStatus, HttpException } from '@nestjs/common'; import { UserService } from './user.service'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto';
@Controller('user') export class UserController { constructor(private readonly userService: UserService) { }
@Post() create(@Body() createUserDto: CreateUserDto) { return this.userService.create(createUserDto); }
@Get() findAll() { const a = process.env.SALT return this.userService.findAll(); }
@Get(':id') findOne(@Param('id') id: string) { const user = this.userService.findOne(+id) if (!user) { throw new HttpException('用户不存在', HttpStatus.NOT_FOUND) } else { return user } }
@Patch(':id') update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) { return this.userService.update(+id, updateUserDto); }
@Delete(':id') remove(@Param('id') id: string) { return this.userService.remove(+id); } }
|