请求拦截
nest g interceptor core/interceptor/transform
// src/core/interceptor/transform.interceptor.ts
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from "@nestjs/common";
import { map, Observable } from "rxjs";
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((res) => {
return {
statusCode: res.statusCode,
message: res.message,
data: res.data,
};
})
);
}
}
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { TransformInterceptor } from "./core/interceptor/transform.interceptor";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 请求拦截
app.useGlobalInterceptors(new TransformInterceptor());
await app.listen(3005);
}
bootstrap();
异常过滤器
- 异常过滤器可以使用以下异常
BadRequestException
UnauthorizedException
NotFoundException
ForbiddenException
NotAcceptableException
RequestTimeoutException
ConflictException
GoneException
PayloadTooLargeException
UnsupportedMediaTypeException
UnprocessableException
InternalServerErrorException
NotImplementedException
BadGatewayException
ServiceUnavailableException
GatewayTimeoutException
nest g filter core/filter/http-exception
// src/filter/http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost } from "@nestjs/common";
import { HttpException } from "@nestjs/common";
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp(); // 获取请求上下文
const response = ctx.getResponse(); // 在请求上下文中获取 response 对象
const request = ctx.getRequest(); // 在请求上下文中获取 request 对象
const status = exception.getStatus(); // 获取异常的状态码
response.status(status).json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { HttpExceptionFilter } from "./core/filter/http-exception.filter";
import { TransformInterceptor } from "./core/interceptor/transform.interceptor";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// 请求拦截
app.useGlobalInterceptors(new TransformInterceptor());
// 异常过滤器
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3005);
}
bootstrap();
接口文档
pnpm install @nestjs/swagger swagger-ui-express -S
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle("管理后台")
.setDescription("管理后台接口文档")
.setVersion("1.0")
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("docs", app, document);
await app.listen(3000);
}
bootstrap();
标签
@ApiTags("文章")
@Controller('cats')
export class CatsController {...}
说明
@ApiOperation({ summary: '创建文章' })
@Post()
传参
// dto/create-cats.dto.ts
export class CreatePostDto {
@ApiProperty({ description: "文章标题" })
readonly title: string;
readonly author: string;
readonly content: string;
readonly cover_url: string;
readonly type: number;
}
// posts.controller.ts
...
import { CreatePostDto } from './dto/create-post.dto';
@ApiOperation({ summary: '创建文章' })
@Post()
async create(@Body() post:CreatePostDto) {...}