NestJs简明教程

配置环境

1.下载并安装nodejs

2.下载并安装vscode

3.为vscode安装中文插件

​ 在扩展应用栏搜索并安装 Chinese (Simplified) Language

4.检查nodejs和npm是否安装成功

node -v
npm -v

5.cnpm安装

npm install cnpm -g --registry=https://registry.npm.taobao.org

检测cnpm安装是否成功

cnpm -v

创建Nestjs项目

安装nest cli

cnpm i -g @nestjs/cli

初始化项目

nest new rpd-api

运行项目

npm run start

数据库ORM连接

  1. 安装TypeORM:

    npm install typeorm --save
    
  2. 需要安装依赖模块 reflect-metadata :

    npm install reflect-metadata --save
    

    在应用里全局引用一下:

    • 比如在app.ts的入口处 require("reflect-metadata")
  3. 你可能需要安装node类型:

    npm install @types/node --save
    
  4. 安装PostgreSQL数据库驱动:

    npm install pg --save
    
  5. 确保你的TypeScript编译器的版本大于2.3,并且在tsconfig.json开启下面设置:

    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    

    同时需要开启编译选项里的lib下的es6或者从@typings安装es6-shim

  6. 在app.module.ts中配置数据库连接

    import { Module } from '@nestjs/common';
    import { TypeOrmModule } from '@nestjs/typeorm';
    @Module({
      imports: [
        TypeOrmModule.forRoot({
          type: 'mysql',
          host: 'localhost',
          port: 3306,
          username: 'root',
          password: 'root',
          database: 'test',
          entities: [__dirname + '/**/*.entity{.ts,.js}'],
          synchronize: true,
        }),
      ],
    })
    export class AppModule {}
    

控制器controller

Nest中的控制器层负责处理传入的请求, 并返回对客户端的响应。

1.新建控制器

D:\Chiaot\nodejs\nestjs\robot-demo-api>nest g controller article

nest g controller role --no-spec

此时会在src文件夹下出现一个article文件夹

2.Get请求

在controller文件中操作

import { Controller, Get } from '@nestjs/common';

@Controller('article')
export class ArticleController {
  //http://127.0.0.1:3000/article/访问
  @Get()
  index(){
    return '这是新闻的articel界面'
  }
  //http://127.0.0.1:3000/article/add访问
  @Get('/add')
  add(){
    return '这是新闻的add界面'
  }
}

3.其他请求

import { Controller, Get,Post,Put, Delete,Patch,Options,Head,All } from '@nestjs/common';


@Controller('article')
export class ArticleController {
  //http://127.0.0.1:3000/article/访问
  @Get()
  index(){
    return '这是新闻的articel界面'
  }
  //http://127.0.0.1:3000/article/add访问
  @Get('/add')
  add(){
    return '这是新闻的add界面'
  }
  @Post()
  indexPost(){
    return {
      message:"这个一个Post请求"
    }
  }
  @Delete()
  indexDelete(){
    return {
      message:"这个一个Delete请求"
    }
  }
  @Put()
  indexPut(){
    return {
      message:"这个一个put请求"
    }
  }
  @Patch()
  indexPatch(){
    return {
      message:"这个一个Patch请求"
    }
  }
  @Options()
  indexOptions(){
    return {
      message:"这个一个Options请求"
    }
  }
  @Head()
  indexHead(){
    return {
      message:"这个一个Head请求"
    }
  }
  @All('/all')
  indexAll(){
    return {
      message:"这个一个All请求"
    }
  }
}

GET(完整请求一个资源)
POST(提交表单)
PUT(上传文件)
DELETE(删除)
PATCH(对某个资源做部分修改)
HEAD(仅请求响应首部)
OPTIONS(返回请求的资源所支持的方法)
TRACE(追求一个资源请求中间所经过的代理)

参数传递

@body()

import { Controller, Get,Post,Put, Delete,Patch,Options,Head,All } from '@nestjs/common';

export class CreateDto {
  title: string
  content: string
  author: string
}


@Controller('article')
export class ArticleController {
  //http://127.0.0.1:3000/article/访问
  @Post()
  indexPost(@Body() data: CreateDto){
    const test = new Test();
    test.title = data.title;
    test.content = data.title;
    test.author = data.author
    return {
      message:"这个一个Post请求"
    }
  }
}

@Param()

import { Controller, Get,Post,Put, Delete,Patch,Options,Head,All } from '@nestjs/common';


@Controller('article')
export class ArticleController {
  //http://127.0.0.1:3000/article/3/
  @Get(':id')
    findOne(@Param() params): string {
      console.log(params.id);
      return `This action returns a #${params.id} cat`;
    }
}

@Query

import { Controller, Get,Post,Put, Delete,Patch,Options,Head,All } from '@nestjs/common';


@Controller('article')
export class ArticleController {
  //http://127.0.0.1:3000/article/?page=1&size=3
  @Get()
  indexPost(@Query() query){
    const page = query.page
    const size = query.size
    return {
      message:"OK"
    }
  }
}

树实体

创建树实体

import {Entity, Tree, Column, PrimaryGeneratedColumn, TreeChildren, TreeParent, TreeLevelColumn} from "typeorm";
@Entity()
@Tree("materialized-path")
export class Category {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

	@TreeChildren()
    children: Category[];
    
	@TreeParent()
    parent: Category;
}

使用树实体

const manager = getManager();
const a1 = new Category("a1");
a1.name = "a1";
await manager.save(a1);

const a11 = new Category();
a11.name = "a11";
a11.parent = a1;
await manager.save(a11);

查询树形结构

const manager = getManager();
const trees = await manager.getTreeRepository(Category).findTrees();

统计子菜单

const manager = getManager();
const menuItem = await manager.getTreeRepository(Menu).findOne({
  where: { id: params.id },
});
console.log(menuItem);

// 统计子菜单
const childrenCount = await manager.getTreeRepository(Menu).countDescendants(menuItem);
console.log(childrenCount);

ORM操作

筛选查询字段

userRepository.find({
    select: ["firstName", "lastName"] 
});

加载子关系或关系主体

userRepository.find({
    relations: ["profile", "photos", "videos"]
});

条件查询

userRepository.find({
    where: {
        firstName: "Timber",
        lastName: "Saw"
    }
});

或查询(可用于不同字段等于同一个值)

userRepository.find({
    where: [{
        firstName: "Timber", 
        lastName: "Saw" 
    }, { 
        firstName: "Stan",
        lastName: "Lee" 
    }]
});

分页查询

Menu.findAndCount({
      skip: (page - 1) * size,
      take: size,
    });

nodejs获取IP

/**
 * @getClientIP
 * @desc 获取用户 ip 地址
 * @param {Object} req - 请求
 */
function getClientIP(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress;
};

GitLab使用

PS D:\RPD\rpd-api> git status
PS D:\RPD\rpd-api> git add .
PS D:\RPD\rpd-api> git commit -m "推送"
PS D:\RPD\rpd-api> git push
PS D:\RPD\rpd-api> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值