35 lines
935 B
TypeScript
35 lines
935 B
TypeScript
import {
|
|
CallHandler,
|
|
ExecutionContext,
|
|
Injectable,
|
|
NestInterceptor,
|
|
} from '@nestjs/common';
|
|
import { Observable, map } from 'rxjs';
|
|
|
|
function skipResponseWrap(url?: string): boolean {
|
|
const path = (url || '').split('?')[0];
|
|
return path.endsWith('/wecom/plugin/openapi.json');
|
|
}
|
|
|
|
@Injectable()
|
|
export class ResponseInterceptor implements NestInterceptor {
|
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
const req = context.switchToHttp().getRequest<{ originalUrl?: string; url?: string }>();
|
|
const res = context.switchToHttp().getResponse<{ headersSent?: boolean }>();
|
|
if (skipResponseWrap(req.originalUrl || req.url)) {
|
|
return next.handle();
|
|
}
|
|
return next.handle().pipe(
|
|
map((data) => {
|
|
if (res.headersSent) return data;
|
|
return {
|
|
code: 0,
|
|
message: 'ok',
|
|
data: data ?? null,
|
|
};
|
|
}),
|
|
);
|
|
}
|
|
}
|
|
|