Class-transformer: feature: add option to convert property name to snake_case or camelCase

Created on 28 Jul 2019  路  6Comments  路  Source: typestack/class-transformer

My json contains some snake_case atributes, but my class is camelCase.
In order to avoid expose naming the class, I'd like something like this:

let users = plainToClass(User, userJson, {snakeToCamel: true});

Thanks!

needs discussion low feature

Most helpful comment

For me a global option to choose the proper casing would be great.

All 6 comments

@arcovoltaico you may need change-object-case

Using the Expose decorator and specifying the name property as an option should do what you want as described at https://github.com/typestack/class-transformer#exposing-properties-with-different-names

It should work for both cases where you plainToClass and classToPlain.

I'm also interested in this feature. Having something on top of Expose.name would be great.

I think both change-object-case and a configuration on plainToClass or classToPlain would be too aggressive.

I'd propose a syntactic sugar for Expose (e.g. name accepting a function to compute exposed name based on class name, so user doesn't have to manually specify each of them, or simply a flag that configures this). Or a decorator on the whole class that shallowly applies a naming scheme to all its fields. This can be useful to have when building class-oriented DTO structures, to be used on the API layer

On why messing with cases, our code style recommends camelCase in the code while our API guideline recommends snake_case for REST payloads.

(Inspiration: scala circe where snake case <> camel case is configured per class)

For me a global option to choose the proper casing would be great.

For the time being using these two libraries:

can be used to wrap the output of classToPlain and pre-input to plainToClass:

plainToClass(camelcaseKeys(plain), ClassName)
snakeCaseKeys(classToPlain(obj))

As mentioned in this thread, there are external tools, which do this and it's 2 lines to wrap class-transformer in a custom function that calls these functions when needed. As a result of this, I am marking this as a low priority. Eventually, it may get landed but not soon. In the meantime, please vote on the initial comment if you want to show your support and don't add extra +1 comments. If you have some comments about the design of the feature feel free to add your two cents.

Was this page helpful?
0 / 5 - 0 ratings