Nest.js学习之路(15)-typeorm(2)新增数据
2019-06-22 本文已影响4人
cbw100
继续在Platform Entity新增列
import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
@Entity('platform') // 指定table name
export class Platform {
// 每新增一个的時候id+1
@PrimaryGeneratedColumn()
id: number;
// @Column为对应的数据库列,或是传入Column Options物件
@Column()
platformname: string;
// 传入Column Options物件设定mapping的列位属性
@Column({
type: 'varchar',
length: 50,
default: '123',
})
title: string;
@Column()
url: string;
@Column({
default: true, // 给预设值
})
isActive: boolean;
}
新建feature文件夹,在feature文件夹下新建platform文件夹,然后,新建platform.controller.ts,platform.module.ts,platform.service.ts三个文件,然后platform.service.ts写入如下代码:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Platform } from 'shared/entity/Platform';
import { Repository } from 'typeorm';
import { PlatformDTO } from 'app.controller';
@Injectable()
export class PlatformService {
constructor(
@InjectRepository(Platform)
private readonly platformRepo: Repository<Platform>,
){}
async addPlatform(data: PlatformDTO){
const platformData = new Platform();
platformData.platformname = data.platformname;
platformData.url = data.url;
platformData.title = data.title;
return await this.platformRepo.save(platformData);
}
}
platform.controller.ts代码如下:
import { Controller, Post, Body } from '@nestjs/common';
import { PlatformDTO } from 'app.controller';
import { PlatformService } from './platform.service';
@Controller('platform')
export class PlatformController {
constructor(private readonly platformService: PlatformService) {}
@Post()
create(@Body() platformDTO: PlatformDTO){
// throw new HttpException('糟糕!您的要求有问题,请联系管理员', HttpStatus.BAD_REQUEST);
return this.platformService.addPlatform(platformDTO);
}
}
platform.module.ts代码如下:
import { Module } from '@nestjs/common';
import { PlatformService } from './platform.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Platform } from 'shared/entity/Platform';
import { PlatformController } from './platform.controller';
@Module({
imports: [TypeOrmModule.forFeature([Platform])],
providers: [PlatformService],
controllers: [PlatformController],
})
export class PlatformModule {}
然后用postman模拟post请求如下:
2018111301.pngmysql管理工具可以看到成功插入的数据
2018111302.png
tuiguang.png推荐一下我的公众号: 【 geekjc 】,微信号: 【 c8706288 】一起学习交流编程知识,分享经验,各种有趣的事。