在上一篇文章中,我们介绍了 NestJS 的微服务架构实现。本文将深入探讨 NestJS 应用的性能优化策略,从应用层到部署层面提供全方位的优化指南。
应用层优化
1. 路由优化
// src/modules/users/users.controller.ts
import { Controller, Get, UseInterceptors, CacheInterceptor } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
@UseInterceptors(CacheInterceptor)
export class UsersController {
constructor(private readonly usersService: UsersService) {}
// 使用路由参数而不是查询参数,提高路由匹配效率
@Get(':id')
async findOne(@Param('id') id: string) {
return this.usersService.findOne(id);
}
// 避免深层嵌套路由
@Get(':id/profile')
async getProfile(@Param('id') id: string) {
return this.usersService.getProfile(id);
}
}
2. 数据序列化优化
// src/interceptors/transform.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { classToPlain } from 'class-transformer';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map(data => {
// 使用 class-transformer 进行高效的数据序列化
return classToPlain(data, {
excludeExtraneousValues: true,
enableCircularCheck: false
});
}),
);
}
}
数据库优化
1. 查询优化
// src/modules/posts/posts.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from './post.entity';
@Injectable()
export class PostsService {
constructor(
@InjectRepository(Post)
private postsRepository: Repository<Post>,
) {}
async findAll(page: number, limit: number) {
// 使用分页查询
const [posts,

最低0.47元/天 解锁文章
1723

被折叠的 条评论
为什么被折叠?



