wvteijlingen / Spine

A Swift library for working with JSON:API APIs. It supports mapping to custom model classes, fetching, advanced querying, linking and persisting.
MIT License
266 stars 109 forks source link

Override default serializedName for Fields #44

Closed jviney closed 8 years ago

jviney commented 8 years ago

Hi,

Thanks for the great work on Spine - it's fantastic :+1: .

The API I'm working with always uses underscored strings for serialization. Rather than specifying the serialized name every time with Attribute().serializedAs("underscored_name_here") I'd instead like to override or subclass Attribute to make this the default.

This seems tricky currently because none of the properties of the Field class are public, and hence can't be overridden or accessed from a subclass inside a my project.

Could the name and serializedName properties be made public? I'm happy to provide a patch. I also tried to provide a different implementation of fieldsFromDictionary, but a similar problem exists because the name field is not accessible. Or perhaps there is a better way to do this?

I'm using the swift-2.0 branch.

Cheers.

wvteijlingen commented 8 years ago

This is good point. We could always make those variables public. I think it might be better however to implement some kind of global FieldNameSerialiser that takes care of converting names to their serialised names. That way you could configure this on the Spine instance instead of having to subclass.

kurko commented 8 years ago

Agree with @wvteijlingen. Inheritance is not the solution, but composition.

aganov commented 8 years ago

+1 for making name and serializedName public

wvteijlingen commented 8 years ago

I'm experimenting with a way to globally configure key formatting. You can find this in the key-formatter branch.

Instead of having to specify the serialised name for every attribute, you can now use a UnderscoredKeyFormatter and let Spine format al your fields for you:

spine.keyFormatter = UnderscoredKeyFormatter()

By default it uses the DasherizedKeyFormatter because dasherized keys are recommended by the JSON:API spec. The serialised name is still there if you need to configure a custom name for a field. The serialised name does not have to be formatted, it will still go through the keyFormatter.

If you happen to check it out, please let me know whether this works for your use case :).

jviney commented 8 years ago

Nice work. The KeyFormatter implementations need some public initialisers though.

wvteijlingen commented 8 years ago

Done!

kurko commented 8 years ago

:clap: :clap: :clap: :clap: