Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Answer

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}`;
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...