繼續在User Entity新增欄位
import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity('My_Users') // 指定table name
export class User {
// 每新增一筆的時候id+1
@PrimaryGeneratedColumn()
id: number;
// @Column為對應的資料庫欄位,或是傳入Column Options物件
@Column()
username: string;
// 傳入Column Options物件設定mapping的欄位屬性
@Column({
type: 'varchar',
length: 50,
})
title: string;
@Column({
default: true, // 給預設值
})
isActive: boolean;
}
修改app.service.ts
export class AppService {
constructor(
@InjectRepository(User)
private readonly userRepo: Repository<User>
){}
...
async addUser(data: UserDTO){
const user = new User();
user.username = data.username;
user.email = data.email;
return await this.userRepo.save(user);
}
}
修改app.controller.ts新增部分
@Post()
@UsePipes(UserDTOValidationPipe)
@ReflectMetadata('roles', ['admin', 'superuser'])
create(@Body() userDTO: UserDTO){
return this.appService.addUser(userDTO); //呼叫appService對資料庫新增資料
}
打開pgadmin4