我试图在 NestJS 的实体中排除一个属性,但不幸的是它似乎没有排除它,当我提出请求时,它包含了该属性
代码:
// src/tasks/task.entity.ts
import { Exclude } from 'class-transformer';
import { User } from 'src/auth/user.entity';
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { TaskStatus } from './task-status.enum';
@Entity()
export class Task {
@PrimaryGeneratedColumn('uuid') id?: string;
@Column() title: string;
@Column() description: string;
@Column() status: TaskStatus;
@Exclude({ toPlainOnly: true }) // -> not working
@ManyToOne((_) => User, (user) => user.tasks, { eager: false })
user: User;
}
src/transform.interceptor.ts
import {
NestInterceptor,
Injectable,
CallHandler,
} from '@nestjs/common';
import { classToPlain } from 'class-transformer';
import { map } from 'rxjs/operators';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(_: any, next: CallHandler<any>) {
return next.handle().pipe(map((data) => classToPlain(data)));
}
}
src/task.service.ts(相关方法)
@Injectable()
export class TasksService {
constructor(@InjectRepository(TaskRepo) private tasksRepo: TaskRepo) {}
// ...
createTask(createTaskDto: CreateTaskDto, user: User) {
return this.tasksRepo.createTask(createTaskDto, user);
}
// ...
}
src/tasks.controller.ts
@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
constructor(private tasksService: TasksService) {}
@Post()
createTask(@Body() createTaskDto: CreateTaskDto, @GetUser() user: User) {
return this.tasksService.createTask(createTaskDto, user);
}
// ...
}
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './transform.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new TransformInterceptor());
await app.listen(3030).catch(console.error);
}
bootstrap().catch(console.error);
@omidh 回答后的 main.ts 文件,不幸的是似乎不起作用
import { ClassSerializerInterceptor, ValidationPipe } from '@nestjs/common';
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './transform.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new TransformInterceptor());
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
await app.listen(3030).catch(console.error);
}
bootstrap().catch(console.error);
我在这里做错了吗?