美文网首页
nestjs(2)连接数据库

nestjs(2)连接数据库

作者: 龙猫_983c | 来源:发表于2020-05-29 20:36 被阅读0次

    安装typeorm与mysql

    npm i --save @nestjs/typeorm typeorm mysql
    

    新建User实体类

    src目录下新建entities目录,用于存放实体类。
    entities目录下新建User实体类,该实体类有idnameage三个字段

    src
    |--entities
    |--|--User.entity.ts

    User.entity.ts:

    import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'
    
    @Entity()
    export class User {
        @PrimaryGeneratedColumn() // 自动生成id
        id: number
    
        @Column()
        name: string
    
        @Column()
        age: number
    }
    

    新建userControlleruserServiceuserModule

    nest g co /user
    nest g s /user
    nest g mo /user
    

    src
    |--entities
    |--user
    |--|--user.controller.ts
    |--|--user.module.ts
    |--|--user.service.ts

    user.controller.ts:
    编写了三个路由,通过监听GET请求,分别调用rootsavegetremove这四个方法

    import { Controller, Get, Query } from '@nestjs/common'
    import { UserService } from './user.service'
    import { User } from '../entities/user.entity'
    
    @Controller('user')
    export class UserController {
        constructor(private readonly userSrvice: UserService) {}
    
        @Get()
        root(): string{
            return this.userSrvice.root()
        }
    
        @Get('save')
        save(@Query() query): any{
    
            console.log(query)
            let user = new User()
            user.name = query.name
            user.age = Number(query.age)
            if(query.id){
                user.id = Number(query.id)
            }
    
            return this.userSrvice.save(user)
        }
    
        @Get('get')
        get(@Query() query): any{
    
            if(query.id){
                query.id = Number(query.id)
            }
            if(query.age){
                query.age = Number(query.age)
            }
            return this.userSrvice.get(query)
        }
        
        @Get('remove')
        remove(@Query() query): any{
    
            if(query.id){
                query.id = Number(query.id)
            }
            if(query.age){
                query.age = Number(query.age)
            }
            return this.userSrvice.remove(query)
        }
    }
    

    user.service.ts:
    实现了对user表的增删查改操作

    import { Injectable } from '@nestjs/common'
    import { User } from '../entities/user.entity'
    import { InjectRepository } from '@nestjs/typeorm'
    import { Repository } from 'typeorm'
    
    @Injectable()
    export class UserService {
    
        constructor(@InjectRepository(User) 
                    private readonly userRepository: Repository<User>) { }
        
        root(): string {
            return 'userService'
        }
    
        // 当user带有id时,save = update;当user没有id时,save = add
        async save(user: User): Promise<any> {
            let res = await this.userRepository.save(user)
            console.log("save: ", res)
    
            return res
        }
    
        async getAll(): Promise<any> {
            let res = await this.userRepository.find()
            console.log("all user: ", res)
    
            return res
        }
    
        async get(option: object): Promise<any> {
            let res = await this.userRepository.find(option)
            // let res = await this.userRepository.find({name: 'longmao'})
            console.log("option user: ", res)
    
            return res
        }
    
        async remove(option: object): Promise<any> {
            let user = await this.userRepository.find(option)
    
            let res = await this.userRepository.remove(user)
    
            console.log("remove: ", res)
    
            return res
        }
    }
    

    user.module.ts:
    通过TypeOrmModule.forFeature([User])获取数据库的user表实例

    import { Module } from '@nestjs/common'
    import { TypeOrmModule } from '@nestjs/typeorm'
    import { UserController } from './user.controller'
    import { UserService } from './user.service'
    import { User } from '../entities/user.entity'
    
    @Module({
      imports: [TypeOrmModule.forFeature([User])],
      controllers: [UserController],
      providers: [UserService]
    })
    export class UserModule {}
    

    连接数据库

    新建一个database和mysql用户供当前项目使用

    mysql -u root -p
    mysql> create database your_database character set utf8;
    mysql> create user 'your_name'@'%' identified by 'your_password';
    mysql> grant all privileges on your_database.* to 'your_name'@'%';
    mysql> flush privileges;
    mysql> exit;
    

    app.module.ts:
    修改app.module.ts中的imports字段,让nest连接上数据库

    import { Module } from '@nestjs/common'
    import { AppController } from './app.controller'
    import { AppService } from './app.service'
    import { UserModule } from './user/user.module'
    import { TypeOrmModule } from '@nestjs/typeorm'
    import { User } from './entities/user.entity'
    
    @Module({
      imports: [TypeOrmModule.forRoot({
        "type": "mysql",
        "host": "localhost",
        "port": 3306,
        "username": "fund_game",
        "password": "fund_game",
        "database": "fund_game",
        "synchronize": true,
        "entities": [User],
      }), UserModule],
      controllers: [AppController],
      providers: [AppService],
    })
    export class AppModule {}
    

    测试运行效果

    npm run start
    

    第一次运行时会自动创建User

    向User表添加数据:浏览器访问localhost:3000/user/save?name=xxx&age=18

    更新User表的数据:浏览器访问localhost:3000/user/get?name=xxx&age=18&id=1

    查询User表的数据:浏览器访问localhost:3000/user/get?name=xxx&age=18

    删除User表的数据:浏览器访问localhost:3000/user/remove?name=xxx&age=18

    相关文章

      网友评论

          本文标题:nestjs(2)连接数据库

          本文链接:https://www.haomeiwen.com/subject/vohxzhtx.html