使用Nest.js与TypeORM搭建Node服务

官方文档

Nest https://www.nestjs.com.cn/

TypeOrm https://typeorm.bootcss.com/

项目demo

https://github.com/KwiTsukasa/starlight-blog-api.git

1.环境准备

1-1.全局安装@nestjs/cli并初始化

npm i -g @nestjs/cli
nest new project-name
**项目目录结构**

main.ts是项目的入口文件.

xxx.module.ts是模块文件的入口.

xxx.service.ts是模块的服务层文件,提供模块的内置方法,需要在module入口文件注入.

xxx.controller.ts是提供模块的接口文件.同上需要在module入口文件注入.

2.安装typeOrm并初始化数据库

npm install typeorm --save
npm install @types/node --save
npm install mysql --save

2-1.新建Entity实体映射类,映射数据库数据

import {
  Entity,//实体注解
  PrimaryGeneratedColumn,//主键列注解
  Column,//列注解
  CreateDateColumn,//创建日期类注解
  UpdateDateColumn,//更新日期类注解
} from 'typeorm';
​
//标记此类为数据库实体类
@Entity()
export class BlogUser {
  //标记此类成员为主键列
  @PrimaryGeneratedColumn()
  user_id: number;
​
    //标记此类成员为列
  @Column()
  user_name: string;
​
​
  @Column({ select: false })
  user_psd: string;
​
​
  @Column()
  user_email: string;
​
​
  @Column()
  user_profile: string;
​
​
  @Column()
  user_img: string;
​
​
  @Column()
  user_links: string;
​
    //标记此类成员为创建日期列
  @CreateDateColumn()
  create_time: Date;
​
    //标记此类成员为更新日期列
  @UpdateDateColumn()
  update_time: Date;
​
​
  @Column()
  is_deleted: boolean;
}

2-2.连接数据库

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
​
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',//数据库类型
      host: 'localhost',
      port: 3306,//数据库端口
      username: 'root',//数据库用户名
      password: 'root',//数据库密码
      database: 'myblog',//数据库
      entities: [__dirname + '/**/*.entity.js'],//实体路径
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

3.创建controller接口

3-1.按模块开发,创建user文件夹存放user模块文件

3-2.包含上述中一个完整模块需要的四个文件

1.module.ts 模块文件的入口文件

2.entity.ts 模块映射数据库实体类文件

3.service.ts 模块内置方法实现文件

4.controller.ts 模块内置接口实现文件

3-3.编写service和controller文件,并在module文件内注入并抛出module文件

1.实现此模块需要的方法

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BlogUser } from './user.entity';
​
@Injectable() //声明这是一个依赖注入类
export class UserService {
  constructor(
    @InjectRepository(BlogUser) //声明这是BlogUser实体的数据库注入映射成员
    private readonly userRepository: Repository<BlogUser>,
  ) {}
​
    //使用用户名查询单个用户
  async find(username: string) {
    const user = await this.userRepository
      .createQueryBuilder('user')//创建一个数据库查询连接
      .addSelect('user.user_psd')//查询符合条件的用户密码
      .where('user.user_name = :user_name', {
        user_name: `${username}`,
      })
      .getOne();//返回一条数据
    return user;
  }
​
    //新增用户
  async save(user){
    const link = await this.userRepository.create(user);
    const save = await this.userRepository.save(link);
    return save;
  }
​
​
}

2.实现此模块接口

import {
  Controller,
  Get,
  Post,
  Body,
  Session,
  Req,
  Res,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { ToolsService } from 'src/utils/tool.service';
import { UserService } from './user.service';
​
​
@Controller('user') //声明这是一个Controller层,并声明此模块接口前缀为user
export class UserController {
  constructor(
    private readonly toolsService: ToolsService,
    private readonly userService: UserService,
  ) {} //注入服务,在module文件内引入的service都需要在构造方法内初始化,否则无法使用
​
​
  @Get('authcode') //当请求该接口时,返回一张随机图片验证码
  async getCode(@Req() req, @Res() res) {
    const svgCaptcha = await this.toolsService.captche(); //创建验证码
    req.session.code = svgCaptcha.text; //使用session保存验证,用于登陆时验证
    res.type('image/svg+xml'); //指定返回的类型
    res.send(svgCaptcha.data); //给页面返回一张图片
  }
​
​
  @Post('/register') //注册接口
  async register(@Body() body, @Session() session, @Res() res) {
    const { code } = body; //用户输入的验证码
    //判断生成验证码和用户输入验证码是否一致
    if (code?.toUpperCase() === session.code?.toUpperCase()) {
      //使用service层查询方法查询对应用户
      const query = await this.userService.find(body.username);
      //如果查到则抛出错误
      if (query) {
        throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
      } else {
        //新增用户
        const save = await this.userService.save({
          user_name: body.username,
          user_psd: body.password,
          user_email: body.useremail,
          user_profile: '',
          user_img: '',
          user_links: '',
          is_deleted: 0,
        });
        //新增成功会返回数据,如果有数据则返回前端200
        if (save) {
          const retn = this.toolsService.res(200, '注册成功', save);
          res.send(retn);
        } else {
          //无数据返回错误
          throw new HttpException('注册失败', HttpStatus.BAD_REQUEST);
        }
      }
    } else {
      //验证码判断错误
      throw new HttpException('验证码错误', HttpStatus.BAD_REQUEST);
    }
  }
}

3.将文件在module.ts文件内引入并抛出module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { BlogUser } from './user.entity';
import { ToolsService } from 'src/utils/tool.service';
​
​
@Module({
  imports: [TypeOrmModule.forFeature([BlogUser])],
  controllers: [UserController],
  providers: [UserService, ToolsService],
  exports: [UserService],
})
export class UserModule {}

4.在app.module.ts项目模块入口文件中中引入自定义模块

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
​
​
@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root',
      database: 'myblog',
      entities: [__dirname + '/**/*.entity.js'],
    }),
    UserModule, //引入自定义模块
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

4.启动node服务

nest start
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
下一篇