创建controller
nest g controller <name>
nest g controller test --flat --no-spec
//在当前目录下创建test.controller.ts控制器
nest generate
根据原理图生成或修改文件
$ nest generate <schematic> <name> [options]
$ nest g <schematic> <name> [options]
Copy to clipboardErrorCopied
参数
参数 描述
<schematic> 原理图或集合:生成原理图。可用的示意图见下表。
<name> 生成的组件的名称。
Schematics
名称 别名 描述
app 在 monorepo 中生成一个新应用程序(如果它是一个标准结构,则转换为 monorepo)。
library lib 在 monorepo 中生成一个新库(如果是标准结构,则转换为 monorepo )。
class cl 生成一个新类。
controller co 生成控制器声明
decorator d 生成自定义装饰器。
filter f 生成过滤器声明。
gateway ga 生成网关声明。
guard gu 生成守卫声明。
interface 生成一个接口。
interceptor in 生成一个拦截器声明。
middleware mi 生成中间件声明。
module mo 生成模块声明。
pipe pi 生成管道声明。
provider pr 生成提供者声明。
resolver r 生成解析器声明。
service s 生成服务声明。
选项:
选项 描述
--dry-run 报告将要进行的更改,但不更改文件系统。别名:- d
--project [project] 应该将该元素添加到项目中。别名:-p
--flat 不要为元素生成文件夹。
--collection [collectionName] 指定逻辑示意图集合。 使用已安装的包含原理图的npm软件包的软包名称。别名:-c
--spec 强制spec文件生成(默认)
--no-spec 禁用spec文件生成
示例
import {
Controller,
Get,
Post,
Body,
Req,
Res,
Session,
Param,
Query,
Headers,
Ip,
HostParam,
Redirect,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { KeywordService } from './keyword.service';
import { CreateKeywordDto } from './dto/create-keyword.dto';
import { Observable, of } from 'rxjs';
@Controller('keyword')
export class KeywordController {
constructor(private readonly keywordService: KeywordService) {}
@Post('/test')
create(@Req() request: Request, @Body() createKeywordDto: CreateKeywordDto) {
return createKeywordDto;
}
//如果@Query()中使用参数如id,则query返回的是id的值,如不使用则返回的是整个对象
@Get()
findOne(@Query() query: string) {
return query;
}
//动态路由,@Param中的参数是用来接收动态的id的,如果不使用参数,则返回的是{id:<实际url中传的值>}
@Get('api/:id')
find(@Param('id') param: string) {
return param;
}
@Get('head')
find2(@Headers('Connection') con: string) {
// console.log(con);
return con;
}
@Get('ip4')
find3(@Ip() ip: string) {
return ip;
}
@Get('host')
find4(@HostParam() host: string) {
return { a: host };
}
//路由通配符
@Get('ap*6')
find5(@HostParam() host: string) {
return { a: 'apiv6' };
}
/*如果注入了@Res,就不能直接return了,可以用res.send()或者res.json()来返回数据
直接使用return,请求会挂起,得不到预期的结果
或者在Res()中使用参数passthrough: true
*/
@Get('re')
find6(@Res({ passthrough: true }) res: Response) {
return { a: 'hello' };
}
//return url会替换掉重定向的url
@Get('/redirect')
@Redirect('https://www.baidu.com', 301)
find7() {
return { url: 'https://www.taobao.com' };
}
@Get('/redirect1')
@Redirect('https://www.taobao.com', 301)
find8() {
return;
}
//异步请求
@Get('/async')
async find9(): Promise<object> {
return new Promise((resolve) => resolve({ a: [1, 2, 3] }));
}
//异步请求
@Get('/ob')
find10(): Observable<object> {
return of({ a: [1, 2, 4] });
}
}