Search code examples
typescriptnestjsmikro-orm

Why do I get `TypeError: Cannot set property length of #<Map> which has only a getter` error?


I have a Nest app where I use (besides other stuff) Fastify, MikroORM and nest-mqtt (actually using it from a fork which fixes it for Nest 8).

Now, the problem lays in using both MikroORM and nest-mqtt: when both are imported in a module (MikroOrmModule.forRoot() and MqttModule.forRoot()), it throws the following error:

TypeError: Cannot set property length of #<Map> which has only a getter
    at _clone (/home/ts/mikro-orm-nest-mqtt/node_modules/clone/clone.js:162:16)
    at _clone (/home/ts/mikro-orm-nest-mqtt/node_modules/clone/clone.js:162:18)
    at clone (/home/ts/mikro-orm-nest-mqtt/node_modules/clone/clone.js:202:10)
    at Function.copy (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/utils/Utils.js:237:36)
    at MetadataDiscovery.discoverDirectories (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/metadata/MetadataDiscovery.js:137:55)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at MetadataDiscovery.findEntities (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/metadata/MetadataDiscovery.js:106:9)
    at MetadataDiscovery.discover (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/metadata/MetadataDiscovery.js:53:9)
    at MikroORM.discoverEntities (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/MikroORM.js:87:25)
    at Function.init (/home/ts/mikro-orm-nest-mqtt/node_modules/@mikro-orm/core/dist/MikroORM.js:42:9)

At first, I thought it is an error in clone (see this issue), however, it does not fail when only one of the the packages (MikroORM or nest-mqtt) is imported into a module.

I suspect that the two packages somehow interact/conflict with each other, however, I am lost.

Here you can find a minimal reproduction. Tested with npm v8.1.2 and node v16.13.1 and node v17.2.0. Also note that it does not matter if the MQTT is actually running. Also change the MikroORM config in src/mikro-orm.config.ts as needed.

Also see this discussion at MikroORM.


Solution

  • @B4nan user at GitHub found the root of this issue: collections package patches some global Node objects like Map, Set, Array. The issue was already reported at mqttjs/MQTT.js#1392.

    Last version without collections dependency is v4.2.8 and last commit without it is 8aa2f8d. Current workaround for me is to use that version until they remove collections from dependencies.

    Update: There is a new PR that should remove collections dependency: mqttjs/MQTT.js#1396.

    Update 2: The PR is already merged and [email protected] is working as expected.