Skip code blocks

This commit is contained in:
Muhsin 2022-12-27 15:48:48 +05:30
parent 9d12826cb0
commit ea5a25934d
2 changed files with 19 additions and 4 deletions

View file

@ -1,12 +1,14 @@
const MESSAGE_VARIABLES_REGEX = /{{(.*?)}}/g;
export const replaceVariablesInMessage = ({ message, variables }) => {
const regex = /{{(.*?)}}/g;
return message.replace(regex, (match, replace) => {
return message.replace(MESSAGE_VARIABLES_REGEX, (match, replace) => {
return variables[replace.trim()]
? variables[replace.trim().toLowerCase()]
: '';
});
};
const skipCodeBlocks = str => str.replace(/```(?:.|\n)+?```/g, '');
export const getFirstName = ({ name }) => {
return name.split(' ')[0];
};
@ -42,9 +44,12 @@ export const getMessageVariables = ({ conversation }) => {
};
export const getUndefinedVariablesInMessage = ({ message, variables }) => {
const regex = /{{(.*?)}}/g;
const matches = message.match(regex);
const messageWithOutCodeBlocks = skipCodeBlocks(message);
const matches = messageWithOutCodeBlocks.match(MESSAGE_VARIABLES_REGEX);
const undefinedVariables = [];
if (!matches) {
return [];
}
matches.forEach(match => {
const variable = match
.replace('{{', '')

View file

@ -123,4 +123,14 @@ describe('#getUndefinedVariablesInMessage', () => {
expect.arrayContaining(['{{contact.twitter}}'])
);
});
it('skip variables in string with code blocks', () => {
const message =
'hey {{contact_name}} how are you? ``` code: {{contact_name}} ```';
expect(
getUndefinedVariablesInMessage({ message, variables }).length
).toEqual(1);
expect(getUndefinedVariablesInMessage({ message, variables })).toEqual(
expect.arrayContaining(['{{contact_name}}'])
);
});
});