Skip to content

Commit

Permalink
fix: improve error message if filter expression in foreach cannot be …
Browse files Browse the repository at this point in the history
…resolved (#6694)

fix: improve error message if filter expression in foreach cannot be
resolved
  • Loading branch information
stefreak authored Dec 6, 2024
1 parent 67b99ac commit 3ff5ee0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
9 changes: 7 additions & 2 deletions core/src/template-string/template-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,12 @@ function handleForEachObject({
const filterResult = resolveTemplateStrings({
value: value[arrayForEachFilterKey],
context: loopContext,
contextOpts,
contextOpts: {
...contextOpts,
// filter expression must be completely resolvable
// TODO: In a future iteration of this code, we should leave the entire $forEach expression unresolved if filter cannot be resolved yet and allowPartial=true.
allowPartial: false,
},
source: {
...source,
path: source.path && [...source.path, arrayForEachFilterKey],
Expand All @@ -460,7 +465,7 @@ function handleForEachObject({
continue
} else if (filterResult !== true) {
throw new TemplateError({
message: `${arrayForEachFilterKey} clause in ${arrayForEachKey} loop must resolve to a boolean value (got ${typeof resolvedInput})`,
message: `${arrayForEachFilterKey} clause in ${arrayForEachKey} loop must resolve to a boolean value (got ${typeof filterResult})`,
path: source.path && [...source.path, arrayForEachFilterKey],
value,
resolved: undefined,
Expand Down
27 changes: 26 additions & 1 deletion core/test/unit/src/template-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2183,7 +2183,32 @@ describe("resolveTemplateStrings", () => {
void expectError(
() => resolveTemplateStrings({ source: undefined, value: obj, context: new GenericContext({}) }),
{
contains: "$filter clause in $forEach loop must resolve to a boolean value (got object)",
contains: "$filter clause in $forEach loop must resolve to a boolean value (got string)",
}
)
})

// TODO: In a future iteration of this code, we should leave the entire $forEach expression unresolved if filter cannot be resolved yet and allowPartial=true.
it("throws if $filter can't be resolved, even if allowPartial=true", () => {
const obj = {
foo: {
$forEach: ["a", "b", "c"],
$filter: "${var.doesNotExist}",
$return: "${item.value}",
},
}

void expectError(
() =>
resolveTemplateStrings({
source: undefined,
value: obj,
context: new GenericContext({ var: { fruit: "banana" } }),
contextOpts: { allowPartial: true },
}),
{
contains:
"invalid template string (${var.doesnotexist}) at path foo.$filter: could not find key doesnotexist under var. available keys: fruit.",
}
)
})
Expand Down

0 comments on commit 3ff5ee0

Please sign in to comment.