Skip to content

Commit

Permalink
returned the spread keyword implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
pazhersh committed May 20, 2024
1 parent 2297f13 commit a8244cb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
13 changes: 13 additions & 0 deletions lib/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,19 @@ const renderRecursively = (inputJson, template, execOptions = {}) => {
if (typeof template === 'object' && template !== null) {
return Object.fromEntries(
Object.entries(template).flatMap(([key, value]) => {
const MY_KEYWORD_ESCAPED = "tempSpreadKeyword\\(\\)";
const keywordMatcher = `^\\{\\{\\s*${MY_KEYWORD_ESCAPED}\\s*\\}\\}$`;

if (key.match(keywordMatcher)) {
const evaluatedValue = renderRecursively(inputJson, value, execOptions);
if (typeof evaluatedValue !== "object") {
throw new Error(
`Evaluated value should be an object if the key is ${key}. Original value: ${value}, evaluated to: ${JSON.stringify(evaluatedValue)}`
);
}
return Object.entries(evaluatedValue);
}

const evaluatedKey = renderRecursively(inputJson, key, execOptions);
if (!['undefined', 'string'].includes(typeof evaluatedKey) && evaluatedKey !== null) {
throw new Error(
Expand Down
4 changes: 4 additions & 0 deletions test/template.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ describe('template', () => {
expect(render({'{{null}}': 'bar'})).toEqual({});
expect(render({'{{""}}': 'bar'})).toEqual({});
expect(render({'{{\'\'}}': 'bar'})).toEqual({});
expect(render({ "{{tempSpreadKeyword()}}": { foo: "bar" } })).toEqual({foo: "bar"});
expect(render({ "{{ tempSpreadKeyword() }}": { foo: "bar" } })).toEqual({foo: "bar"});
});
it('recursive templates should work', () => {
const json = { foo: 'bar', bar: 'foo' };
Expand Down Expand Up @@ -165,6 +167,8 @@ describe('template', () => {
expect(() => { jq.renderRecursively({foo: "bar"}, '{{.foo + 1}}', {throwOnError: true}) }).toThrow("jq: error: string (\"bar\") and number (1) cannot be added");
expect(() => { jq.renderRecursively({}, '{{foo}}/{{bar}}', {throwOnError: true}) }).toThrow("jq: compile error: foo/0 is not defined at <top-level>, line 1:");
expect(() => { jq.renderRecursively({}, '/{{foo}}/', {throwOnError: true}) }).toThrow("jq: compile error: foo/0 is not defined at <top-level>, line 1:");
expect(() => { jq.renderRecursively({}, { "{{ tempSpreadKeyword() }}": "str" }, { throwOnError: true }) })
.toThrow('Evaluated value should be an object if the key is {{ tempSpreadKeyword() }}. Original value: str, evaluated to: "str"');
})
})

0 comments on commit a8244cb

Please sign in to comment.