From 6489025273cb704dbd7b297b3908dc70a1804ddc Mon Sep 17 00:00:00 2001 From: Lucas Bustamante Date: Tue, 18 Jan 2022 19:36:38 -0300 Subject: [PATCH] Hydrate from snake_case or camelCase, depending on applied transformers --- .../model-transformer-transformation.ts | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/js/api/src/framework/transformations/model-transformer-transformation.ts b/packages/js/api/src/framework/transformations/model-transformer-transformation.ts index ba4b5415f74..f5b53085987 100644 --- a/packages/js/api/src/framework/transformations/model-transformer-transformation.ts +++ b/packages/js/api/src/framework/transformations/model-transformer-transformation.ts @@ -74,12 +74,27 @@ export class ModelTransformerTransformation< T extends Model > implements ModelT * @return {*} The transformed properties. */ public toModel( properties: any ): any { - const val = properties[ this.property ]; + let propertyName = this.property; + let val = properties[ propertyName ]; + + if ( ! val ) { + /* + * Properties are defined in snake_case format, but the properties in the models are camelCase. + * Due to how the hydration of the model works, using TypeScript's Partial, the properties object + * might have been transformed from snake_case to camelCase already, so we try to convert + * the property name to camelCase before giving up. + */ + propertyName = propertyName.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function (_match, chr) { + return chr.toUpperCase(); + }); + val = properties[ propertyName ]; + } + if ( val ) { if ( Array.isArray( val ) ) { - properties[ this.property ] = val.map( ( v ) => this.transformer.toModel( this.modelClass, v ) ); + properties[ propertyName ] = val.map( ( v ) => this.transformer.toModel( this.modelClass, v ) ); } else { - properties[ this.property ] = this.transformer.toModel( this.modelClass, val ); + properties[ propertyName ] = this.transformer.toModel( this.modelClass, val ); } }