darrachequesne / notepack

A fast Node.js implementation of the latest MessagePack spec
MIT License
75 stars 19 forks source link

Support for custom encoders #18

Open zbjornson opened 5 years ago

zbjornson commented 5 years ago

msgpack-lite supports Custom Extension Types (Codecs). There's a project that I'd love to switch to this faster lib, but it uses a codec.

(Thanks for maintaining this fork btw!)

msgpack-lite's API for that is okay and maybe the best choice for an easy migration path, but you could also consider some class API like:

// impl
exports.ToMsgPackSym = const ToMsgPackSym = Symbol("notepack.tomsgpack");
// in `_encode`
if (typeof value[ToMsgPackSym] === "function") {
  bytes.push(value.constructor[MsgPackTypeSym], ...value[ToMsgPackSym](value));
}

// usage
class MyClass {
  static [notepack.MsgPackTypeSym] = 0x00;
  [notepack.ToMsgPackSym]() {
    return /*something*/;
  }
  [notepack.FromMsgPackSym](bytes) {
    return new MyClass(/*something*/);
  }
}
notepack.registerType(MyClass);
Domiii commented 2 years ago

Agreed. Not being able to encode basic built-ins, such as Symbol, is a big downer. Probably will have to fork our own versions to patch that in...