关于拦截器想请教老师

来源:11-17 拦截器进阶(序列化):敏感数据如何处理?

LinkeZ

2023-08-15

在写代码的时候发现在查询数据时通过relation获取的关联关系entity中的数据无法正常拦截,代码如下:
blog.controller.ts

  @Get()
  @UseInterceptors(new SerializeInterceptor(GetAllBlogDto))
  findAll() {
    return this.blogService.findAll();
  }

blog.Service.ts

...
  async findAll() {
    return await this.blogRepository.find({
      where: { isDelete: false, published: true },
      relations: ['image'],
    });
  }

GetAllBlogDto.ts

import { Expose } from 'class-transformer';
import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
import { Image } from '../../image/entities/image.entity';

class ImageDto extends Image {
  @IsString()
  @IsNotEmpty()
  @Expose()
  url: string;
}

export class GetAllBlogDto {
  @IsNumber()
  @IsNotEmpty()
  @Expose()
  id: number;

  @IsString()
  @IsNotEmpty()
  @Expose()
  blogTitle: string;

  @IsString()
  @IsNotEmpty()
  @Expose()
  summary: string;

  @IsString()
  @IsNotEmpty()
  @Expose()
  image: ImageDto;
}

通过上面代码想要获取这样的数据:

[
	{
		id:1,
		blogTitle: **,
		summary:**,
		image: {
			url: **,
		}
	},
	{....}
]

但获取到的数据中image一直为空对象,除了在image的entity中添加@Expose()外,请问老师还有没有其它办法?
非常感谢!

写回答

1回答

Brian

2023-08-16

0
2
Brian
回复
LinkeZ
那之后有的controller也许就不需要这个字段——你可以考虑,在后面的controller再创建一个dto
2023-08-22
共2条回复

NestJS 入门到实战 前端必学服务端新趋势

近几年快速发展的Node.js框架,掌握未来前端工程师后端开发能力

569 学习 · 238 问题

查看课程