nest typeorm mysql 练习

  • 编写数据层、控制层、服务层、模块层
  • 在模块层中引入 数据层、 控制层、 服务层
  • 在服务层中引入 数据层 使用 增删改查 处理数据
  • 在控制层中引入 服务层 实现功能
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 // 引入mysql数据类
		])
	],
	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() // 路径不写默认为当前页的主路由 user
	async createUser(
		@Body() data: {[key: string]: any}
	): Promise<UserEntity> {
		// 返回增加的用户数据
		return await this.userService.createUser(data)
	}

	@Get("get") // /user/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()
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值