Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

nestjs - Typeorm - Transform Response

I'm using Typeorm with NestJS, is there a way to pass in a dynamic value into the Column transformer?

I've got this post entity file:

export class Post extends EntityBase {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => PostType, (postType) => postType.id)
  postType: PostType;

  @Column()
  name: string;

  @Column()
  dateStart: Date;

  @Column()
  dateEnd: Date;

  @Column({ select: false })
  status: number;

  @Column({
    transformer: {
      to(n) {
        return n;
      },
      from(n) {
        return configService.getCDNUrl() + n;
      },
    },
  })
  imageList: string;

  @Column()
  slug: string;
}

I'm waiting to prefix the images with the full CDN URL, currently, this appends the CDN URL correctly as it's a static value so i pull the value from the configservice so i do get https://mycdn.com/image.jpg

However my images are stored in folders for each client so what i actually need it https://mycdn.com/{{clientId}}/image.jpg - Each request to the API does contain the clientId, is there a way to pass this information into the entity or repository to transform the response (or we can pick the clientId from postType.clientId) or will have to manually transform it in the service?

question from:https://stackoverflow.com/questions/65643649/typeorm-transform-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For anyone looking at this in the future, I found that I can use the @AfterLoad() decorator to update the value, can even access the related entities

@AfterLoad()
  setCdnUrl() {
    this.imageList = `${configService.getCDNUrl()}${
      this.postType.clientId
    }/content/${this.imageList}`;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...