◐ Shell
clean mode source ↗

Call toJSON() on non-ext objects when it exists by kevincennis · Pull Request #188 · msgpack/msgpack-javascript

Currently, @msgpack/msgpack does not automatically call .toJSON() on objects which define that method.

Since JSON and msgpack have significant overlap in semantics and intent, and toJSON() is a signal from an object that says "this is how I want to be serialized", I believe it makes sense to use toJSON() when it exists (after exhausting possible extensions).

The concrete use-case for me was mongodb.ObjectId – which returns a simple string from toJSON(), but otherwise looks like:

{
  _bsontype: string,
  id: Uint8Array
}

Effectively, this change helps msgpack more closely match the behavior of JSON.stringify().


It wasn't entirely clear to me where these tests should go. There's not much in the suite for testing the encode side. Most of the tests seem to sort of implicitly test encoding while calling themselves decode tests, so I've stuck with that convention here.