From b8734ecb609ad41c3c117b88cab8dc818d82e62a Mon Sep 17 00:00:00 2001 From: Chau Tran Date: Wed, 6 Apr 2022 23:14:43 -0500 Subject: [PATCH] fix(core): adjust getFlatteningPaths to flatten more as needed --- packages/core/src/lib/utils/get-path.ts | 45 +++++++++++++++++++++---- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/packages/core/src/lib/utils/get-path.ts b/packages/core/src/lib/utils/get-path.ts index 07c2843d0..319a8f42e 100644 --- a/packages/core/src/lib/utils/get-path.ts +++ b/packages/core/src/lib/utils/get-path.ts @@ -36,10 +36,7 @@ export function getFlatteningPaths( ); let trueFirstPartOfSource = first; let stopIndex = 0; - let found = Object.prototype.hasOwnProperty.call( - src, - trueFirstPartOfSource - ); + let found = hasProperty(src, trueFirstPartOfSource); if (!found) { for (let i = 0, len = paths.length; i < len; i++) { @@ -48,9 +45,7 @@ export function getFlatteningPaths( trueFirstPartOfSource, paths[i], ]); - if ( - Object.prototype.hasOwnProperty.call(src, trueFirstPartOfSource) - ) { + if (hasProperty(src, trueFirstPartOfSource)) { stopIndex = i + 1; found = true; break; @@ -62,6 +57,38 @@ export function getFlatteningPaths( return srcPath; } + const restPaths = splitSourcePaths.slice( + stopIndex + 1, + splitSourcePaths.length + 1 + ); + const transformedRestPaths = + sourceNamingConvention.transformPropertyName(restPaths); + + if ( + restPaths.length > 1 && + !hasProperty( + src[trueFirstPartOfSource] as Record, + transformedRestPaths + ) && + hasProperty( + src[trueFirstPartOfSource] as Record, + sourceNamingConvention.transformPropertyName([restPaths[0]]) + ) + ) { + // still has more flattening to do: eg: bookAuthorName -> ['Author', 'Name'] + // transformedRestPaths (authorName) does not exist on source + // first of rest paths (author) does exist on source + + return [ + trueFirstPartOfSource, + ...getFlatteningPaths( + src[trueFirstPartOfSource] as Record, + getPath([transformedRestPaths], namingConventions), + namingConventions + ), + ]; + } + return [ trueFirstPartOfSource, sourceNamingConvention.transformPropertyName( @@ -69,3 +96,7 @@ export function getFlatteningPaths( ), ]; } + +function hasProperty(obj: Record, property: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, property); +}