web-01-api/src/common/interceptors/transform.interceptor.ts
2026-06-22 10:26:29 +08:00

34 lines
814 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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>;
}),
);
}
}