Gowhich

Durban's Blog

这里记录下使用Nest.js中,在控制器中如何添加所有请求方式的方法

第一种请求方式Get

1
2
3
4
5
6
7
8
9
@Get()
findAll() {
return 'This action will return all dogs';
}

@Get(':id')
findOne(@Param('id') id: string) {
return `This action will return one ${id} dog`;
}

第二种请求方式Post

1
2
3
4
@Post()
create(@Body() createDogDto: CreateDogDto) {
return `This action will add a dog`;
}

第三种请求方式Put

1
2
3
4
@Put(':id')
update(@Param('id') id: string, @Body() updateDogDto: UpdateDogDto) {
return `This action will update a dog`;
}

第四种请求方式Delete

1
2
3
4
@Delete(':id')
remove(@Param('id') id: string) {
return `This action will remote a dog`;
}

完整的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
} from '@nestjs/common';
import { CreateDogDto } from 'src/create-dog.dto';
import { UpdateDogDto } from 'src/update-dog.dto';

@Controller('dogs')
export class DogsController {
@Get()
findAll() {
return 'This action will return all dogs';
}

@Get(':id')
findOne(@Param('id') id: string) {
return `This action will return one ${id} dog`;
}

@Post()
create(@Body() createDogDto: CreateDogDto) {
return `This action will add a dog`;
}

@Put(':id')
update(@Param('id') id: string, @Body() updateDogDto: UpdateDogDto) {
return `This action will update a dog`;
}

@Delete(':id')
remove(@Param('id') id: string) {
return `This action will remote a dog`;
}
}

控制器payloads请求

如果通过Post请求来接收客户端的payloads参数

Nest.js通过使用@Body装饰器

首先创建一个DTO类,create-cats.dto.ts

1
2
3
4
5
export class CreateCatDto {
name: string;
age: number;
bread: string;
}

然后修改create方法

1
2
3
4
5
6
7
import { CreateCatDto } from 'src/create-cats.dto';

@Post()
async create(@Body() createCatDto: CreateCatDto) {
console.log(createCatDto);
return 'This action will create a new cat';
}

运行npm run start:dev

我们测试下

1
2
$ curl -d 'name=durban&age=12&bread=ddd' http://127.0.0.1:3000/cats
This action will create a new cat

可以看到console.log的输出结果如下

1
{ name: 'durban', age: '12', bread: 'ddd' }

异步机制

Nest.js也是支持现在javascript的异步机制的,async/await

同时每个async函数必须返回一个Promise

看个简单的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
import { Controller, Get, HostParam } from '@nestjs/common';

@Controller('account')
export class AccountController {
@Get()
getInfo(@HostParam('account') account) {
return account;
}
@Get('all')
async findAll(): Promise<any[]> {
return [];
}
}

同时Nest.js还可以处理observable streams.

例子如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { Controller, Get, HostParam } from '@nestjs/common';
import { Observable, of } from 'rxjs';

@Controller('account')
export class AccountController {
@Get()
getInfo(@HostParam('account') account) {
return account;
}

@Get('all')
findAll(): Observable<any[]> {
return of([]);
}
}

上面两个例子在访问的时候都会直接返回一个空数组

子域路由

@Controller装饰器提供了一个host选项可用,主要用来判断这个控制器在被访问的时候,限制具体的域名来访问

代码如下

1
2
3
4
5
6
7
8
@Controller('cats')
@Controller({ host: 'api.gowhich.com' })
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action will returns all cats';
}
}

再举个例子

1
2
3
4
5
6
7
8
@Controller('cats')
@Controller({ host: 'api.gowhich.com' })
export class CatsController {
@Get()
getInfo(@HostParam('account') account) {
return account;
}
}

开始记录前的说明

表名:users

表中字段名:id,name,age,ctime

创建索引

创建语句语法

db.COLLECTION_NAME.ensureIndex(keys[,options]) 用于3.0及以下版本

db.COLLECTION_NAME.createIndex(keys[,options])用于3.0及以上版本

keys:要建立索引的参数列表。

如:{KEY:1},其中key表示字段名,1表示升序排序,也可使用使用数字-1降序。
options:可选参数,表示建立索引的设置。

可选值如下:
background: Boolean - 在后台建立索引,以便建立索引时不阻止其他数据库活动。默认值为false。
unique: Boolean - 创建唯一索引。默认值 false。
name: String - 指定索引的名称。如果未指定,MongoDB会生成一个索引字段的名称和排序顺序串联。
partialFilterExpression: document - 如果指定,MongoDB只会给满足过滤表达式的记录建立索引.
sparse: Boolean - 对文档中不存在的字段数据不启用索引。默认值是 false。
expireAfterSeconds: integer - 指定索引的过期时间
storageEngine: document - 允许用户配置索引的存储引擎

第一个情况,创建单字段索引

1
db.users.createIndex({"name":1})

第二个情况,创建多字段索引

1
db.users.createIndex({"name":1,"age":1})

第三种情况,创建索引加可选项,这个情况建议多使用

1
db.users.createIndex({"name":1,"age":1}, {background: 1})

查看索引

记录几种常用的方法

  1. getIndexes()方法可以用来查看集合的所有索引,
  2. getIndexKeys()方法查看索引键。
  3. totalIndexSize()查看集合索引的总大小,
  4. getIndexSpecs()方法查看集合各索引的详细信息

删除索引

记录下常用方法

  1. dropIndex()方法用于删除指定的索引
  2. dropIndexes()方法用于删除全部的索引

重定向

Nest.js提供了一种方式可以重定向路由

方式可以通过使用装饰器@Redirect和res.redirect

这里记录下如何使用装饰器来重定向

1
2
3
4
5
6
7
8
9
@Get('items')
@Redirect('https://www.gowhich.com', 302)
getItems(@Query('version') version) {
if (version && version == 5) {
return {
url: 'https://www.gowhich.com/cats/items/v5',
};
}
}

当访问http://127.0.0.1:3000/cats/items,URI会被重定向到https://www.gowhich.com

当访问http://127.0.0.1:3000/cats/items?version=5,URI会被重定向到https://www.gowhich.com/cats/items/v5

获取路由参数

这里说的路由参数值的是,当访问cats/1这样的路由的时候,能否获取到1这个参数值

当然Nest.js也提供了一个非常好用的装饰器@Param

这个装饰器,我们可以使用两种方式来获取到参数

第一种

1
2
3
4
@Get(':id')
getOne(@Param() param): string {
return `This action return id #${param.id}`;
}

第二种

1
2
3
4
@Get(':name')
getName(@Param('name') name): string {
return `This action return name #${name}`;
}

如何设置状态码

Nest.js通过装饰器@HttpCode来设置状态码,状态码默认200

1
2
3
4
5
@Get()
@HttpCode(204)
itemError(): string {
return 'This action return 204 error';
}

HttpCode@nestjs/common包中导入

如何设置Header信息

Header信息是可以自定义的,Nest.js也提供了一个@Header装饰器来帮助我们添加Header信息

1
2
3
4
5
@Get()
@Header('Cache-Control', 'none')
itemCustomHeader(): string {
return 'This action custom header';
}

Header@nestjs/common包中导入

我们在使用php的框架的时候,比如laravel、yii2等

会用到composer这个安装包的工具,类似于nodejs的npm、python的pip

但是总有因为各种限制,安装包的时候不能访问到指定的资源

这个时候就有各种的第三方镜像资源可以供我们使用

我想说的是,第三方资源没问题,但是网上写文章的人就有问题了,以为你只告诉了如何配置,但是如果历史已经安装成功的,会有相关的安装历史记录的记录

比如composer会有composer.lock

比如nvm会有package-lock.json等类似的,方便下次安装的时候,保证对应的版本号不变

今天记录下如下正确的使用composer

1、安装composer,已经安装的可以跳过

2、配置源镜像

可以像下面这样全局配置

1
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

也可以像下面这样配置当前项目

1
composer config repo.packagist composer https://mirrors.aliyun.com/composer/

如果遇到不想用的情况,可以使用下面的命令取消

1
composer config -g --unset repos.packagist
1
composer config --unset repos.packagist

依次对应上面的不情况的配置

3、清缓存

1
composer clear

4、更新composer.lock

1
composer update --lock

5、开始使用新的源来安装包

1
composer install

Nest.js控制中的Resources

前面介绍了路由中如何通过GET方式访问路由,Nest.js还支持Post、Delete、Patch、Options、Head和All等

下面看下如何使用Post

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { Controller, Get, Post, Req, Request } from '@nestjs/common';

@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action will returns all cats';
}

@Post()
create(): string {
return 'This action will create a new cat';
}
}

项目运行起来后,做个简单的测试

1
2
$ curl -d '' http://127.0.0.1:3000/cats
This action will create a new cat

可以看到,post请求的时候访问到了create()方法

Route通配符

看个简单的例子

1
2
3
4
@Get('x*z')
find() {
return 'This action uses a wildcard';
}

然后启动项目做下面几个测试

1
2
$ curl http://127.0.0.1:3000/cats/xyz
This action uses a wildcard
1
2
$ curl http://127.0.0.1:3000/cats/xyyz
This action uses a wildcard
1
2
$ curl http://127.0.0.1:3000/cats/xyyzz
This action uses a wildcard

从上面的输出可以观察到,输出的内容都是一致的,说明访问的路由其实调用了同一个方法

'x*z'路由将会匹配xyz,xyyz,xyyzz等,?,+,*,()都可以被用在路由的路径中

一个控制器的目的是接收来自应用的一个请求

那么如何来处理这个请求,以及如何接收一个请求

Nest.js提供了一个Request Object

先看下之前写的一个例子

1
2
3
4
5
6
7
8
9
import { Controller, Get, Render, Res } from '@nestjs/common';

@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action will returns all cats';
}
}

我们想知道如何在这个例子中获取request中的参数

修改代码如下

1
2
3
4
5
6
7
8
9
import { Controller, Get, Render, Req, Request } from '@nestjs/common';

@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action will returns all cats';
}
}

http obejct包括了所有http的属性,比如http query 参数、http header、body、parameters等

但是在Nest.js中已经提供了专用的装饰器比如@Body@Query

其他的罗列在下面了

@Request() req
@Response(), @Res()* res
@Next() next
@Session() req.session
@Param(key?: string) req.params / req.params[key]
@Body(key?: string) req.body / req.body[key]
@Query(key?: string) req.query / req.query[key]
@Headers(name?: string) req.headers / req.headers[name]
@Ip() req.ip
0%