Search code examples
typescriptts-jest

How to map, with automapper typescript, a "Map" or "Record" interface with a complex object?


I'm using the autommaper-ts with ttypscript plugin to auto-generate the mapping. https://automapperts.netlify.app/

For simple objects, this works well, but when I use complex ones, like: Record<string, any> or Map<string, AnotherObject> these does not work well.

  1. An example with Map<string, SampleItem>:
export class SampleItem {
  type: string;
  name: string;
  example?: unknown;

  constructor(data?: SampleItem) {
    Object.assign(this, data);
  }
}

class Entity {
  @AutoMap(() => SampleItem)
  sample: Map<string, SampleItem>;

  @AutoMap(() => Object)
  details: Record<string, any>;
}

This is a test diff when I compare the both: image

The payload for the problem above:

{
   sample: {
      sampleOne: {
        name: 'sample name',
        type: SampleTypes.STRING,
        example: 'sample example',
      } as SampleItem,
    },
    description: 'description'
}

  1. Another problem happens when I use a complex object for the details field:
{
    description: { des: 'description' } as Record<string, any>,
}
Original error: Error: Mapping is not found for function String() { [native code] } and function String() { [native code] }

    at setMember (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:379:15)
    at map (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:439:9)
    at mapReturn (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:291:10)
    at Proxy.<anonymous> (/home/fabiofilho/Projects/project/node_modules/@automapper/core/index.cjs:691:31)

Some details - using the ttypescript:

"dependencies": {
    "@automapper/classes": "^8.7.5",
    "@automapper/core": "^8.7.5",
    "@automapper/mikro": "^8.7.5",
    "@automapper/nestjs": "^8.7.5",
    "@automapper/pojos": "^8.7.5",
    "@automapper/sequelize": "^8.7.5",
}

module.exports = {
  [...]
  globals: {
    'ts-jest': {
      compiler: 'ttypescript',
    },
  },
};


Solution

  • There is no problem at all, I was using the wrong parameters before to map the object, so the mistake was mine.