streamich / json-joy

json-joy is a library that implements cutting-edge real-time and collaborative editing algorithms and utilities for JSON data models, with a focus on developing the JSON CRDT (Conflict-free Replicated Data Type) specification and implementation.
https://jsonjoy.com/libs/json-joy-js
Apache License 2.0
784 stars 16 forks source link

customization to have Map, BigNumber #777

Closed anymos closed 1 week ago

anymos commented 1 week ago

Hello:

What would be the best course of action if I want to have that part working :

`let _map=new Map(); _map.set('key',{ o:1 })

    const pojo = {
        id: 123,
        foo: 'bar',
        tags: ['a', 'b', 'c'],
        bn:new BigNumber(3),
        map:_map
    };
    const encoder = new JsonEncoder(new Writer());
    const encoded = encoder.encode(pojo);
    const decoder = new JsonDecoder();
    const decoded = decoder.read(encoded);

    console.log(`json:decoded:`,decoded);`

bn and map are null

streamich commented 1 week ago

You can extends the JsonEncoder and JsonDecoder classes.

In JsonEncoder overwrite the encodeUnknown method:

class MyEncoder extends JsonEncoder {
  encodeUnknown(value) {
    if (typeof value === 'bigint') {
      return String(value);
    }
    return super.encodeUnknown(value);
  }
}

In the JsonDecoder overwrite the readAny method:

class MyDecoder extends JsonDecoder {
  public readAny(): unknown {
    this.skipWhitespace();
    const reader = this.reader;
    // Try to decode a bigint using the `reader`,
    // if it is not a bigint, try to decode all other values:
    return super.readAny();
  }
}
anymos commented 1 week ago

Awesome :) thank you

anymos commented 1 week ago

I believe it can be closed, will try and revert back if any other pb .

Thank you again !