Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(templates): export the placeholder name reader

Yudhi Armyndharisf1228297d610
diff --git a/src/common/utils/template-render.spec.ts b/src/common/utils/template-render.spec.ts
index 6ffd539fe..8e42fffa8 100644
--- a/src/common/utils/template-render.spec.ts
+++ b/src/common/utils/template-render.spec.ts
@@ -1,4 +1,4 @@
-import { renderedLength, renderTemplate, TemplateRenderError } from './template-render';
+import { renderedLength, renderTemplate, TemplateRenderError, templateVariableNames } from './template-render';
describe('renderTemplate', () => {
describe('canonical double-brace {{name}}', () => {
@@ -119,3 +119,23 @@ describe('a variable that is not a string', () => {
expect(toString).toHaveBeenCalledTimes(1);
});
});
+
+describe('templateVariableNames', () => {
+ it.each([
+ ['', []],
+ ['no placeholders', []],
+ ['Hi {{name}} and {name}', ['name', 'name']],
+ ['{{ first.name }}-{{order-id}}-{plain}', ['first.name', 'order-id', 'plain']],
+ ['{{}} { } {a b} {{a b}}', []],
+ ])('lists the variables of %p', (body, names) => {
+ expect(templateVariableNames(body)).toEqual(names);
+ });
+
+ it('names exactly the placeholders the renderer substitutes', () => {
+ const body = 'a {{x}} b {y} c {{ z.w }} d {{-}} e {not a var} f {{q}}{r}';
+ const names = templateVariableNames(body);
+ const vars = Object.fromEntries(names.map(name => [name, '#']));
+ // Every listed name is replaced, and nothing else is: the unlisted braces are left as written.
+ expect(renderTemplate(body, vars)).toBe('a # b # c # d # e {not a var} f ##');
+ });
+});
diff --git a/src/common/utils/template-render.ts b/src/common/utils/template-render.ts
index 917dcd8d2..daaba7254 100644
--- a/src/common/utils/template-render.ts
+++ b/src/common/utils/template-render.ts
@@ -15,6 +15,11 @@
// surrounding whitespace — so existing single-brace bulk content renders bit-for-bit as before.
const PLACEHOLDER_PATTERN = /\{\{\s*([\w.-]+)\s*\}\}|\{(\w+)\}/g;
+/** The variable names a template mentions, in order of appearance, read with the syntax the renderer substitutes. */
+export function templateVariableNames(body: string): string[] {
+ return Array.from(body.matchAll(PLACEHOLDER_PATTERN), match => match[1] ?? match[2]);
+}
+
/** A template that cannot be rendered for a reason the caller can report, such as a value with no text form. */
export class TemplateRenderError extends Error {}