wwayne/es6-enum

JSON serialization

pronebird opened this issue · 7 comments

Would be great to somehow be able to serialize/deserialize enums.

May i ask about the use case?

I used it with Redux which I used to serialize into local storage. However, It's been a while and I don't use es6-enum anymore so I cannot really provide any meaningful feedback at this point.

I'm trying to use Enum as a set of constants of statuses. But when I'm trying to save an object to mongo it's not converted to valid JSON. Here is an example:

const STATUS = Enum('initialCreate', 'gettingEstimates', 'errorInEstimate');
const obj = {
  amount: 0,
  status: STATUS.initialCreate
};
new OrderModel({ db }).insertOne(obj);

I think that's because of Symbol -> String conversion.
Do I use the Enum library wrong?

@MEGApixel23 STATUS.initialCreate is actually a Symbol, so it can be converted to a string because Symbol has the method toString. I doubt mongo was trying to call JSON.stringify on the object and the Symbol is not able to be converted correctly because Symbol doesn't support toJSON natively.

I can implement toJSON to es6-enum, but the thing is, I haven't found any way of dealing with JSON.parse on a Symbol, that means only serialize(JSON.stringify) can be implemented on es6-enum which is obviously meaningless. So I would suggest you just use string instead of es6-enum(e.g. status: 'initialCreate') or we are making things too complicated

@wwayne It .toString() method is used on a Symbol it gets converted to Symbol(some-string).

Example:

constole.log( Symbol('some-string').toString() ); // "Symbol(some-string)"

And it's a bit unexpected result for me. Seems that I'm trying to use Symbol type in a way it wasn't designed originally. So I ended up with using just ordinary constants.

But anyway, thanks a lot for your explanation and I fully agree with your reasoning!

@MEGApixel23 Welcome :)

We've got that solved with the eventual switch to Flow which has built in enums.