Skip to content

Commit

Permalink
refactor: convertToObjectMapping
Browse files Browse the repository at this point in the history
  • Loading branch information
koladilip committed Jun 16, 2024
1 parent 3ca5a9b commit 563b324
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions src/utils/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,6 @@ function processFlatMappingPart(
currentOutputPropsAST: ObjectPropExpression[],
): ObjectPropExpression[] {
const outputPart = flatMapping.outputExpr.parts[partNum];

if (
outputPart.type !== SyntaxType.SELECTOR ||
!outputPart.prop?.value ||
Expand Down Expand Up @@ -222,33 +221,44 @@ function processFlatMappingPart(
return objectExpr.props;
}

function processFlatMapping(flatMapping, currentOutputPropsAST) {
function handleRootOnlyOutputMapping(flatMapping: FlatMappingAST, outputAST: ObjectExpression) {
outputAST.props.push({
type: SyntaxType.OBJECT_PROP_EXPR,
value: {
type: SyntaxType.SPREAD_EXPR,
value: flatMapping.inputExpr,
},
} as ObjectPropExpression);
}

function processFlatMapping(flatMapping, outputAST: ObjectExpression) {
let currentOutputPropsAST = outputAST.props;
for (let i = 0; i < flatMapping.outputExpr.parts.length; i++) {
currentOutputPropsAST = processFlatMappingPart(flatMapping, i, currentOutputPropsAST);
}
}

function validateMapping(flatMapping: FlatMappingAST) {
if (flatMapping.outputExpr.type !== SyntaxType.PATH) {
throw new Error(
`Invalid object mapping: output=${flatMapping.output} should be a path expression`,
);
}
if (flatMapping.outputExpr.parts.length === 0) {
currentOutputPropsAST.push({
type: SyntaxType.OBJECT_PROP_EXPR,
value: {
type: SyntaxType.SPREAD_EXPR,
value: flatMapping.inputExpr,
},
} as ObjectPropExpression);
return;
}
for (let i = 0; i < flatMapping.outputExpr.parts.length; i++) {
currentOutputPropsAST = processFlatMappingPart(flatMapping, i, currentOutputPropsAST);
}
}
/**
* Convert Flat to Object Mappings
*/
export function convertToObjectMapping(flatMappingASTs: FlatMappingAST[]): ObjectExpression {
export function convertToObjectMapping(
flatMappingASTs: FlatMappingAST[],
): ObjectExpression | PathExpression {
const outputAST: ObjectExpression = createObjectExpression();
for (const flatMapping of flatMappingASTs) {
processFlatMapping(flatMapping, outputAST.props);
validateMapping(flatMapping);
if (flatMapping.outputExpr.parts.length > 0) {
processFlatMapping(flatMapping, outputAST);
} else {
handleRootOnlyOutputMapping(flatMapping, outputAST);
}
}

return outputAST;
Expand Down

0 comments on commit 563b324

Please sign in to comment.