Skip to content

Commit

Permalink
fixing variable parsing code (#2642)
Browse files Browse the repository at this point in the history
  • Loading branch information
joe-ayoub-segment authored Dec 12, 2024
1 parent efc8a1a commit 5913cd9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ const emailTemplate = `<!DOCTYPE html>
<p>Thank you for joining <strong>{{user.leagueName}}</strong>! Your current leagues are:</p>
<p>Hello {{insert name "default=Customer"}}! Thank you for contacting us about {{insert businessName "your big business"}}.</p>
<p>Hello {{insert name "default=Customer"}}! Thank you for contacting us about {{insert businessName 'your small business' "x = this text should not become variable" }}.</p>
{{root.user.username | default: "Unknown"}}
<ul>
{{#each user.currentLeagues}}
<li><strong>{{this.leagueName}}: {{this.leagueParticipants}} members</strong></li>
Expand Down Expand Up @@ -176,8 +179,9 @@ describe('Sendgrid.sendEmail', () => {
const tokens = extractVariables(emailTemplate)
expect(tokens).toMatchObject([
'user',
'login_url',
'name',
"businessName",
'login_url',
'supportPhone',
'scoreOne',
'scoreTwo',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,22 @@ export function extractVariables(content: string | undefined): string[] {
}

const removeIfStartsWith = ['if', 'unless', 'and', 'or', 'equals', 'notEquals', 'lessThan', 'greaterThan', 'each']

const removeIfMatch = ['else', 'if', 'this', 'insert', 'default', 'length', 'formatDate']

const regex1 = /{{(.*?)}}/g // matches handlebar expressions
const regex2 = /[#/]?"?[\w."]+"?/g // matches words. Deliberately includes " characters which will be removed later
const regex1 = /{{(.*?)}}/g // matches handlebar expressions. e.g. {{root.user.username | default: "Unknown"}}
const regex2 = /(["']).*?\1/g // removes anything between quotes. e.g. {{root.user.username | default: }}
const regex3 = /[#/]?[\w.]+/g // matches words only. e.g. root.user.username , default

const words = [
...new Set(
[...content.matchAll(regex1)]
.map((match) => match[1])
.join(' ')
.match(regex2)
[...content.matchAll(regex1)].map(match => match[1])
)
]
.map(word =>
word.replace(regex2, '').trim()
)
.join(' ')
.match(regex3) ?? []

const variables = [
...new Set(
Expand Down

0 comments on commit 5913cd9

Please sign in to comment.