介绍:在 NestJs 中,你可以自定义一个统一的响应封装来支持成功、错误和分页响应。
代码示例:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
// 统一成功响应的数据结构
export interface SuccessResponse<T> {
code: number;
message: string;
data: T;
}
// 统一错误响应的数据结构
export interface ErrorResponse {
code: number;
message: string;
}
// 统一分页响应的数据结构
export interface PaginatedResponse<T> {
code: number;
message: string;
data: T[];
total: number;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, SuccessResponse<T>> {
intercept(context: ExecutionContext, next: CallHandler): Observable<SuccessResponse<T>> {
return next.handle().pipe(
map(data => ({
code: 0, // 自定义成功响应的状态码
message: '请求成功', // 自定义成功响应的消息
data,
})),
);
}
}
@Injectable()
export class ErrorInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
catchError(error => {
return throwError({
code: error.status || 500, // 自定义错误响应的状态码,默认为 500
message: error.message || '服务器错误', // 自定义错误响应的消息,默认为 '服务器错误'
});
}),
);
}
}
然后,在你的控制器中使用这些拦截器来实现统一的响应封装。代码示例:
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor, ErrorInterceptor, SuccessResponse, ErrorResponse, PaginatedResponse } from './common';
@Controller('users')
@UseInterceptors(TransformInterceptor, ErrorInterceptor)
export class UsersController {
// 成功响应示例
@Get(':id')
getUserById(): SuccessResponse<User> {
const user: User = {
id: 1,
name: 'John Doe',
email: 'johndoe@example.com',
};
return user;
}
// 错误响应示例
@Get(':id')
getUserById(): ErrorResponse {
throw new NotFoundException('用户未找到');
}
// 分页响应示例
@Get()
getAllUsers(): PaginatedResponse<User> {
const users: User[] = [
{
id: 1,
name: 'John Doe',
email: 'johndoe@example.com',
},
{
id: 2,
name: 'Jane Smith',
email: 'janesmith@example.com',
},
// ...
];
return {
data: users,
total: users.length,
};
}
}
这样,当你调用这些接口时,它们会自动使用定义的拦截器进行统一的响应封装,返回相应的数据结构。你可以自行根据需求修改拦截器中的状态码、消息和数据结构等内容。