- 编写数据层、控制层、服务层、模块层
- 在模块层中引入 数据层、 控制层、 服务层
- 在服务层中引入 数据层 使用 增删改查 处理数据
- 在控制层中引入 服务层 实现功能
UserEntity
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
UpdateDateColumn
} from "typeorm"
@Entity({ name: "user" })
export class User {
@PrimaryGeneratedColumn({
type: "int",
name: "id",
comment: "主键ID",
})
id: number
@Column({
type: "varchar",
name: "username",
length: 16,
nullable: true,
unique: true,
comment: "用户名"
})
username: string
@Column({
type: "varchar",
name: "password",
length: 20,
nullable: false,
default: 123456,
comment: "密码"
})
password: string
@Column({
type: "tinyint",
name: "is_del",
default: () => 0,
comment: "0 未删除, 1 已删除"
})
isDel: number
@CreateDateColumn({
type: "timestamp",
name: "create_at",
nullable: false,
comment: "创建时间"
})
createAt: Date
@UpdateDateColumn({
type: "timestamp",
name: "update_at",
comment: "更新时间",
nullable: false
})
updateAt: Date
}
UserModule
import { Module } from "@nest/common"
import { TypeOrmModule } from "@nestjs/typeorm"
import { UserEentity } from "./user.entity"
import { UserService } from "./user.service"
import { UserController } from "./user.controller"
@Module({
imports: [
TypeOrmModule.forFeature([
UserEntity
])
],
controllers: [
UserController
],
providers: [
UserService
]
})
export class UserModule {}
UserController
import { Controller, Body, Post, Get } from "@nestjs/common"
import { UserService } from "./user.service"
import { UserEntity } from "./user.entity"
@Controller("user")
export class UserController {
constructor (
private readonly userService: UserService
) {}
@Post()
async createUser(
@Body() data: {[key: string]: any}
): Promise<UserEntity> {
return await this.userService.createUser(data)
}
@Get("get")
async userList(): Promise<UserEntity[]> {
return await this.userService.userList()
}
}
UserService
import { Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } "typeorm"
import { UserEntity } from "./user.entity"
@Injectable()
export class UserService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>
) {}
async createUser(data: { [key: string]: any }): Promise<UserEntity> {
return await this.userRepository.save(data)
}
async userList(): Promise<UserEntity[]> {
return await this.userRepository.find()
}
}