34 lines
814 B
TypeScript
34 lines
814 B
TypeScript
import {
|
||
CallHandler,
|
||
ExecutionContext,
|
||
Injectable,
|
||
NestInterceptor,
|
||
} from '@nestjs/common';
|
||
import { Observable } from 'rxjs';
|
||
import { map } from 'rxjs/operators';
|
||
import { ApiResponse } from '../dto/api-response.dto';
|
||
|
||
/**
|
||
* 全局统一响应拦截器
|
||
* 把所有 controller 返回值包装成 { code, msg, data } 结构
|
||
*/
|
||
@Injectable()
|
||
export class TransformInterceptor<T>
|
||
implements NestInterceptor<T, ApiResponse<T>>
|
||
{
|
||
intercept(
|
||
context: ExecutionContext,
|
||
next: CallHandler<T>,
|
||
): Observable<ApiResponse<T>> {
|
||
return next.handle().pipe(
|
||
map((data) => {
|
||
// 如果已经是 ApiResponse,则原样返回
|
||
if (data instanceof ApiResponse) {
|
||
return data;
|
||
}
|
||
return ApiResponse.success(data) as ApiResponse<T>;
|
||
}),
|
||
);
|
||
}
|
||
}
|