kriszyp / msgpackr

Ultra-fast MessagePack implementation with extension for record and structural cloning / msgpack.org[JavaScript/NodeJS]

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`toJSON()` method of subclass of Set is ignored when used with `moreTypes: true` option

panmenghan opened this issue · comments

With the {moreTypes: true} option, the subclass of Set with toJSON() defined, the toJSON() is ignored by the Packr.
Also tested with Map, the toJSON() method of subclass of Map is called correctly.

import {Packr, Unpackr} from 'msgpackr'

const MSGPACK_OPTIONS = {moreTypes: true}

class MapWithToJSON extends Map {
  toJSON() {
    console.log('MapWithToJSON.toJSON.called')
    return [...this.entries()]
  }
}

class SetWithToJSON extends Set {
  toJSON() {
    console.log('SetWithToJSON.toJSON.called')
    return [...this.values()]
  }
}

function test() {
  const packer = new Packr(MSGPACK_OPTIONS)
  const unpacker = new Unpackr(MSGPACK_OPTIONS)
  const original = {
    mapWithToJSON: new MapWithToJSON([
      ['a', 1],
      ['b', 2],
    ]),
    setWithToJSON: new SetWithToJSON([1, 2]),
    set: new Set([1, 2]),
  }

  console.log('original', original)
  //  original {
  //   mapWithToJSON: MapWithToJSON(2) [Map] { 'a' => 1, 'b' => 2 },
  //   setWithToJSON: SetWithToJSON(2) [Set] { 1, 2 },
  //   set: Set(2) { 1, 2 }
  // }

  console.log('msgpackr', unpacker.unpack(packer.pack(original)))
  // MapWithToJSON.toJSON.called
  // msgpackr {
  //   mapWithToJSON: [ [ 'a', 1 ], [ 'b', 2 ] ],
  //   setWithToJSON: Set(2) { 1, 2 },   <---- the problem!!!, the toJSON() method is not called
  //   set: Set(2) { 1, 2 }
  // }

  console.log('json', JSON.parse(JSON.stringify(original)))
  // MapWithToJSON.toJSON.called
  // SetWithToJSON.toJSON.called
  // json {
  //   mapWithToJSON: [ [ 'a', 1 ], [ 'b', 2 ] ],
  //   setWithToJSON: [ 1, 2 ],
  //   set: {}
  // }
}

test()