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
安装nest cli
cnpm i -g @nestjs/cli
初始化项目
nest new rpd-api
运行项目
npm run start
安装TypeORM:
npm install typeorm --save
需要安装依赖模块 reflect-metadata
:
npm install reflect-metadata --save
在应用里全局引用一下:
require("reflect-metadata")
你可能需要安装node类型:
npm install @types/node --save
安装PostgreSQL数据库驱动:
npm install pg --save
确保你的TypeScript编译器的版本大于2.3,并且在tsconfig.json
开启下面设置:
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
同时需要开启编译选项里的lib
下的es6
或者从@typings
安装es6-shim
在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 {}
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(追求一个资源请求中间所经过的代理)
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请求"
}
}
}
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`;
}
}
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);
筛选查询字段
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,
});
/**
* @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;
};
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>