Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
panmenghan opened this issue Nov 9, 2023 · 0 comments

Comments

@panmenghan
Copy link

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant