msgpack-javascript icon indicating copy to clipboard operation
msgpack-javascript copied to clipboard

support for type information using typescript decorators ?

Open prunelsigma opened this issue 6 years ago • 3 comments
trafficstars

Hi, Thank for your work on this library. I have one question:
Do you have some plans to add features to serialize/deserialize using specific types? like the type reflection in C# using the typescript decorators and reflect-metadata api. https://www.typescriptlang.org/docs/handbook/decorators.html. The goal is to be able to encode/decode some class in a custom way like with IMessagePackFormatter<T> in https://github.com/neuecc/MessagePack-CSharp.

prunelsigma avatar Nov 12 '19 10:11 prunelsigma

Thanks. This seems an interesting idea, but decorators are not standardized yet, so I won't implement them for the time being.

gfx avatar Nov 19 '19 03:11 gfx

@prunelsigma I have made a very basic version of this over here: https://github.com/utiliread/ur-msgpack Feel free to use any part of it.

See the tests for example use: https://github.com/utiliread/ur-msgpack/blob/master/src/deserialize.spec.ts

For example:

class ModelWithArrayKey {
    @msgpackKey(0)
    number!: number;
    @msgpackKey(1)
    string!: string;
    @msgpackKey(2)
    numberArray!: number[];
    @msgpackKey(3)
    stringArray!: string[];
}

const result = deserialize(ModelWithArrayKey, decode(encode([1337, "hello", [1, 2], ["a", "b"]])))

rmja avatar Feb 19 '21 07:02 rmja

I've created a similar library which supports unions (similar to MessagePack C#), over at https://github.com/camnewnham/msgpack-decorators

Example definition:

abstract class Animal {
  @key(0)
  name: string;
  @key(1)
  legs: number;
}

@union(0, Animal)
class Lizard extends Animal{
  @key(3)
  scales: number
}

@union(1, Animal)
class Bird extends Animal {
  @key(4)
  feathers: number
}

Example usage:

const animal: Animal = new Lizard();
animal.legs = 2;

const encoded:Uint8Array = encode(animal, Animal);
const decoded:Animal = decode(encoded, Animal);

This is a peer to @msgpack/msgpack - in future it would be more efficient to fork and integrate directly, and even better would be codegen like protobufjs.

camnewnham avatar Mar 02 '22 06:03 camnewnham