26 lines
894 B
TypeScript
26 lines
894 B
TypeScript
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
|
import { Observable } from 'rxjs';
|
|
import { map } from 'rxjs/operators';
|
|
import { ApiResponse } from '@artveris/shared';
|
|
|
|
// 将控制器返回值统一包裹为 { code, message, 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) => {
|
|
if (
|
|
data &&
|
|
typeof data === 'object' &&
|
|
'code' in (data as object) &&
|
|
'message' in (data as object) &&
|
|
'data' in (data as object)
|
|
) {
|
|
return data as unknown as ApiResponse<T>;
|
|
}
|
|
return { code: 0, message: 'success', data: (data ?? null) as T | null };
|
|
}),
|
|
);
|
|
}
|
|
}
|