f-miyu / Plugin.CloudFirestore

MIT License
121 stars 44 forks source link

fix: serialize and deserialize enums #47

Open artem-metliakov opened 4 years ago

artem-metliakov commented 4 years ago

Fix the Enums support. Fix some misspellings.

Now they're saved in FireStore as strings.

This fixes #46

f-miyu commented 3 years ago

Thank you for your pull request. I'm sorry, but I can't merge this as it is. Your implement is enum to string but I would rather implement enum to int. However, I want to support enum to string optionally and consider creating ConverterAttribute which is an attribute for specifying a converter to convert a type to other type such as enum to string.

public class Data
{
    [Converter(typeof(EnumStringConverter))]
     TypeEnum Type { get; set; }
}
artem-metliakov commented 3 years ago

Thank you for your answer. Why do you prefer ints rather than strings?

If I do support for custom ConverterAttribute for converting types to other types: at first the value will be converted to another type by Converter and then will be converted to native type by FieldValueExtensions.ToNativeFieldValue. Am I get you right?

RGBPlaza commented 3 years ago

Being able to convert between string and enum would be an absolute dream since that would allow for great compatibility with databases that also interact with typescript projects which use string unions as the equivalent. This couldn't come sooner!

x2764tech commented 3 years ago

I'd rather have Enums as strings in Firestore, but I can see value in storing enums as numbers. Some other things to thing about:

Having a Converter for this would allow much broader customisation, but whether these are .Net Converters or a custom converter type (like JSON.NET) is a decision to be made. In my mind, a converter should convert to and from the underlying representation, and the library should expose functionality to handle known cases.

f-miyu commented 3 years ago

I have updated this library. After all, I decided enum is converted to integer by default because of the fallowing reasons.

But I have implemented the EnumStringConverter which simply converts enum to string by ToString.

Usage:

public class Data
{
    [DocumentConverter(typeof(EnumStringConverter))]
     TypeEnum Type { get; set; }
}

You can create a custom converter in the same way as EnumStringConverter.

RGBPlaza commented 3 years ago

Thank you, this is really nice 🔥🔥😋