Wednesday 18 November 2020

automapper-ts returns empty object using typeorm

I'm trying to use automapper-ts to map from dto to entity and vice versa. The creation of the mappings seems fine to me but when I try to map I always get an object without values.

The config:

        automapper
            .createMap(CityDTO, City)
            .forMember('createdBy', (opts: AutoMapperJs.IMemberConfigurationOptions) => opts.ignore())
            .forMember('createdAt', (opts: AutoMapperJs.IMemberConfigurationOptions) => opts.ignore())
            .forMember('updatedBy', (opts: AutoMapperJs.IMemberConfigurationOptions) => opts.ignore())
            .forMember('updatedAt', (opts: AutoMapperJs.IMemberConfigurationOptions) => opts.ignore());
        // These are properties present in the entity but not in the DTO

And this is the mapping method:

  const fromCityDtoToCity = (source: CityDTO, destination?: City): City => {
    if (!destination) {
      destination = new City();
    }

    // This produces 'source name' and 'source population'
    Object.keys(source).forEach((key) => console.log('source', key));
    // This never runs, it seems it doesn't have any key
    Object.keys(destination).forEach((key) => console.log('destination', key));

    destination = automapper.map(CityDTO, City, source);

    return destination;
  };

As ORM I'm using typeorm. This is the entity class:

  export class EntityBase extends BaseEntity {
    @PrimaryGeneratedColumn({ name: 'Id' })
    id: number;

    @Column({ name: 'CreatedBy', length: 50 })
    createdBy: string;

    @CreateDateColumn({ name: 'CreatedAt' })
    createdAt: Date;

    @Column({ name: 'UpdatedBy', nullable: true, length: 50 })
    updatedBy: string;

    @CreateDateColumn({ name: 'UpdatedAt', nullable: true })
    updatedAt: Date;
  }

  @Entity('Cities')
  export class City extends EntityBase {
    @Column({ name: 'Name', length: 50 })
    name: string;

    @Column({ name: 'Population' })
    population: number;
  }


from automapper-ts returns empty object using typeorm

No comments:

Post a Comment