msgpack / msgpack-javascript

@msgpack/msgpack - MessagePack for JavaScript / msgpack.org[JavaScript/TypeScript/ECMA-262]
https://msgpack.org/
ISC License
1.29k stars 161 forks source link

Encoder / Decoder classes dont work with `new ExtensionCodec()` for handling Set and Map in typescript #236

Open noahehall opened 11 months ago

noahehall commented 11 months ago

issue:

how do we use ExtensionCodec with En/Decoder classes? they dont accept an options 2nd param

even if we pass the extensionCodec in the constructor, and continue as normal, encoding fails

import {
  Encoder,
  Decoder,
  encode,
  decode,
  ExtensionCodec,
} from "@msgpack/msgpack";

// Encoder && Decoder doesnt work with extensioncodec
const extensionCodec = new ExtensionCodec();
const decoder = new Decoder({ extensionCodec });
const encoder = new Encoder({ extensionCodec });

// Set<T>
const SET_EXT_TYPE = 0; // Any in 0-127
extensionCodec.register({
  type: SET_EXT_TYPE,
  encode: (object: unknown): Uint8Array | null => {
    if (object instanceof Set) {
      // return encoder.encode([...object], { extensionCodec }); // <-- when using encode fn
      return encoder.encode([...object]);
    } else {
      return null;
    }
  },
  decode: (data: Uint8Array) => {
    // const array = decoder.decode(data, { extensionCodec }) as Array<unknown>; // <-- when using decode fn
    const array = decoder.decode(data) as Array<unknown>;
    return new Set(array);
  },
});

// Map<T>
const MAP_EXT_TYPE = 1; // Any in 0-127
extensionCodec.register({
  type: MAP_EXT_TYPE,
  encode: (object: unknown): Uint8Array => {
    if (object instanceof Map) {
      //  return encoder.encode([...object], { extensionCodec }); // <---- when using encode fn
      return encoder.encode([...object]);
    } else {
      return null;
    }
  },
  decode: (data: Uint8Array) => {
    //  const array = decoder.decode(data, { extensionCodec }) as Array< // <--- when using decode fn
    const array = decoder.decode(data) as Array<
      [unknown, unknown]
    >;
    return new Map(array);
  },
});

 original Map(2) {
  "nirvai": Map(8) {
    "updated_at": 2023-11-19T13:43:27.000Z,
    "callsign": "nirvai",
    "created_at": 2023-11-19T13:43:27.000Z,
    "id": "15796774249725404537",
    "label": "player",
    "type": "org",
    "created_by": "15796774249725404537",
    "email": "nirvai@nirv.ai",
  },
  "knoa": Map(8) {
    "updated_at": 2023-11-19T13:43:27.000Z,
    "callsign": "knoa",
    "created_at": 2023-11-19T13:43:27.000Z,
    "id": "11806400024551464037",
    "label": "player",
    "type": "human",
    "created_by": "15796774249725404537",
    "email": "noah@ogobar",
  },
}
RangeError: Extra 475 of 630 byte(s) found at buffer[155]
  --> GET /v1/players 500 8ms