From f6c2acc3983cfbd57d2de39092e6398960930003 Mon Sep 17 00:00:00 2001 From: Andy Edwards Date: Mon, 21 Dec 2020 14:13:27 -0600 Subject: [PATCH] feat: create template.asyncExpression --- src/__tests__/template-test.js | 10 +++++++++- src/template.js | 22 +++++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/__tests__/template-test.js b/src/__tests__/template-test.js index 6e7b6940..fb614b1a 100644 --- a/src/__tests__/template-test.js +++ b/src/__tests__/template-test.js @@ -108,7 +108,6 @@ while (i < 10) { ) .toEqual(expected); }); - it('correctly parses expressions without any interpolation', () => { const expected = 'function() {}'; @@ -121,6 +120,15 @@ while (i < 10) { .toEqual(expected); }); + for (const parser of ['babel', 'babylon', 'flow', 'ts', 'tsx']) { + it(`asyncExpression correctly parses expressions with await -- ${parser}`, () => { + const expected = '{\n bar: await baz\n}' + const j = jscodeshift.withParser(parser) + + expect(j(j.template.asyncExpression`{\n bar: await baz\n}`).toSource()).toEqual(expected) + }) + } + describe('explode arrays', () => { it('explodes arrays in function definitions', () => { diff --git a/src/template.js b/src/template.js index d2c0f0d2..f55cc971 100644 --- a/src/template.js +++ b/src/template.js @@ -149,5 +149,25 @@ module.exports = function withParser(parser) { return expression; } - return {statements, statement, expression}; + function asyncExpression(template/*, ...nodes*/) { + template = Array.from(template); + if (template.length > 0) { + template[0] = 'async () => (' + template[0]; + template[template.length - 1] += ')'; + } + + const expression = statement.apply( + null, + [template].concat(Array.from(arguments).slice(1)) + ).expression.body; + + // Remove added parens + if (expression.extra) { + expression.extra.parenthesized = false; + } + + return expression; + } + + return {statements, statement, expression, asyncExpression}; }