Nest 初始化 typeORM
首先创建一个nestjs 项目
nest new temp_nest-typeorm -p npm
安装 @nestjs/typeorm typeorm mysql2
npm install --save @nestjs/typeorm typeorm mysql2
@nestjs/typeorm 就是把 typeorm api 封装了一层的包
它提供了一个模块,我们在入口引入下并配置 (记得提前创建数据库 typeorm_test)
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
import { User } from './user/entities/user.entity';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '123',
database: 'typeorm_test',
synchronize: true,
logging: true,
entities: [],
poolSize: 10,
connectorPackage: 'mysql2',
extra: {
authPlugin: 'sha256_password',
},
}),
UserModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
生成创建一个 resource
➜ temp_nest-typeorm git:(main) nest g resource user
➜ temp_nest-typeorm git:(main) ✗ nest g resource user
? What transport layer do you use? REST API
? Would you like to generate CRUD entry points? Yes
CREATE src/user/user.controller.spec.ts (556 bytes)
CREATE src/user/user.controller.ts (883 bytes)
CREATE src/user/user.module.ts (241 bytes)
CREATE src/user/user.service.spec.ts (446 bytes)
CREATE src/user/user.service.ts (607 bytes)
CREATE src/user/dto/create-user.dto.ts (30 bytes)
CREATE src/user/dto/update-user.dto.ts (169 bytes)
CREATE src/user/entities/user.entity.ts (21 bytes)
UPDATE package.json (2071 bytes)
UPDATE src/app.module.ts (730 bytes)
✔ Packages installed successfully.
完善一下 user.entity
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity({
name: 'nest_user',
})
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
name: 'nest_name',
length: 50,
})
name: string;
}
将 User Entity 配置dataSource 的 Entity
启动
➜ temp_nest-typeorm git:(main) ✗ npm run start
> temp_nest-typeorm@0.0.1 start
> nest start
[Nest] 48600 - 2024/12/30 10:43:26 LOG [NestFactory] Starting Nest application...
Ignoring invalid configuration option passed to Connection: authPlugin. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection
[Nest] 48600 - 2024/12/30 10:43:26 LOG [InstanceLoader] TypeOrmModule dependencies initialized +58ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [InstanceLoader] UserModule dependencies initialized +0ms
query: SELECT VERSION() AS `version`
query: START TRANSACTION
query: SELECT DATABASE() AS `db_name`
query: SELECT `TABLE_SCHEMA`, `TABLE_NAME`, `TABLE_COMMENT` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA` = 'typeorm_test' AND `TABLE_NAME` = 'nest_user'
query: SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'typeorm_test' AND `TABLE_NAME` = 'typeorm_metadata'
query: CREATE TABLE `nest_user` (`id` int NOT NULL AUTO_INCREMENT, `nest_name` varchar(50) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB
query: COMMIT
[Nest] 48600 - 2024/12/30 10:43:26 LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +102ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RoutesResolver] AppController {/}: +3ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/, GET} route +2ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RoutesResolver] UserController {/user}: +0ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/user, POST} route +0ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/user, GET} route +0ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/user/:id, GET} route +1ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/user/:id, PATCH} route +0ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [RouterExplorer] Mapped {/user/:id, DELETE} route +0ms
[Nest] 48600 - 2024/12/30 10:43:26 LOG [NestApplication] Nest application successfully started +1ms
注入 EntityManager 增删改查
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { User } from './entities/user.entity';
@Injectable()
export class UserService {
@InjectEntityManager()
private manager: EntityManager;
create(createUserDto: CreateUserDto) {
this.manager.save(User, createUserDto);
}
findAll() {
return this.manager.find(User);
}
findOne(id: number) {
return this.manager.findOneBy(User, {
id,
});
}
update(id: number, updateUserDto: UpdateUserDto) {
this.manager.save(User, {
id: id,
...updateUserDto,
});
}
remove(id: number) {
this.manager.delete(User, id);
}
}
发送请求测试一下
首先 controller 需要对dto校验
安装验证依赖
npm i class-transformer class-validator
完善 CreateUserDto 和 controller 的参数验证
import { IsNotEmpty, MaxLength } from 'class-validator';
export class CreateUserDto {
@IsNotEmpty()
@MaxLength(50)
name: string;
}
@Post()
create(@Body(new ValidationPipe()) createUserDto: CreateUserDto) {
return this.userService.create(createUserDto);
}
验证完成后
插入数据
多来几条
SELECT * FROM nest_user;
id | nest_name |
---|---|
1 | cccc |
2 | cccc1 |
3 | cccc2 |
4 | cccc3 |
5 | cccc4 |
6 | cccc5 |
查询全部
根据 Id 查询
query: SELECT `User`.`id` AS `User_id`, `User`.`nest_name` AS `User_nest_name` FROM `nest_user` `User`
query: SELECT `User`.`id` AS `User_id`, `User`.`nest_name` AS `User_nest_name` FROM `nest_user` `User` WHERE ((`User`.`id` = ?)) LIMIT 1 -- PARAMETERS: [3]
试试 update 传入 Id
先查再更新
query: SELECT `User`.`id` AS `User_id`, `User`.`nest_name` AS `User_nest_name` FROM `nest_user` `User` WHERE `User`.`id` IN (?) -- PARAMETERS: [3]
query: START TRANSACTION
query: UPDATE `nest_user` SET `nest_name` = ? WHERE `id` IN (?) -- PARAMETERS: ["cccc33333",3]
query: COMMIT
再试试删除:
query: DELETE FROM `nest_user` WHERE `id` IN (?) -- PARAMETERS: [3]
注入 Respository
直接用 EntityManager 的缺点是每个 api 都要带上对应的 Entity:
Nest 对这个做了封装,在 user 模块引入 TypeOrmModule.forFeature 对应的动态模块,传入 User 的 Entity:
src/user/user.module.ts
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 {}
就可以在模块里注入 Repository 了:
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { User } from './entities/user.entity';
@Injectable()
export class UserService {
@InjectEntityManager()
private manager: EntityManager;
@InjectRepository(User)
private userRepository: Repository<User>;
create(createUserDto: CreateUserDto) {
this.manager.save(User, createUserDto);
}
findAll() {
return this.userRepository.find();
}
findOne(id: number) {
return this.userRepository.findOneBy({
id,
});
}
update(id: number, updateUserDto: UpdateUserDto) {
this.userRepository.save({
id: id,
...updateUserDto,
});
}
remove(id: number) {
this.userRepository.delete(id);
}
}
评论区