From 036a58b74f3a4d9cc4b75bdd52d062991c579e3b Mon Sep 17 00:00:00 2001 From: Dilip Kola Date: Mon, 2 Sep 2024 15:35:14 +0530 Subject: [PATCH] feat: add util for applying json string template --- src/v0/util/index.js | 6 ++++++ src/v0/util/index.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/v0/util/index.js b/src/v0/util/index.js index db84fb0627..e1fe8ee942 100644 --- a/src/v0/util/index.js +++ b/src/v0/util/index.js @@ -2268,6 +2268,11 @@ const validateEventAndLowerCaseConversion = (event, isMandatory, convertToLowerC const applyCustomMappings = (message, mappings) => JsonTemplateEngine.createAsSync(mappings, { defaultPathType: PathType.JSON }).evaluate(message); +const applyJSONStringTemplate = (message, template) => + JsonTemplateEngine.createAsSync(template.replace(/{{/g, '${').replace(/}}/g, '}'), { + defaultPathType: PathType.JSON, + }).evaluate(message); + /** * Gets url path omitting the hostname & protocol * @@ -2293,6 +2298,7 @@ module.exports = { addExternalIdToTraits, adduserIdFromExternalId, applyCustomMappings, + applyJSONStringTemplate, base64Convertor, batchMultiplexedEvents, checkEmptyStringInarray, diff --git a/src/v0/util/index.test.js b/src/v0/util/index.test.js index 31ea490b25..a8d13ab873 100644 --- a/src/v0/util/index.test.js +++ b/src/v0/util/index.test.js @@ -9,6 +9,7 @@ const { combineBatchRequestsWithSameJobIds, validateEventAndLowerCaseConversion, } = require('./index'); +const exp = require('constants'); // Names of the utility functions to test const functionNames = [ @@ -691,6 +692,29 @@ describe('extractCustomFields', () => { }); }); +describe('applyJSONStringTemplate', () => { + it('should apply JSON string template to the payload', () => { + const payload = { + domain: 'abc', + }; + const template = '`https://{{$.domain}}.com`'; + + const result = utilities.applyJSONStringTemplate(payload, template); + expect(result).toEqual('https://abc.com'); + }); + + it('should apply JSON string template to the payload multiple times', () => { + const payload = { + domain: 'abc', + subdomain: 'def', + }; + const template = '`https://{{$.subdomain}}.{{$.domain}}.com`'; + + const result = utilities.applyJSONStringTemplate(payload, template); + expect(result).toEqual('https://def.abc.com'); + }); +}); + describe('get relative path from url', () => { test('valid url', () => { expect(utilities.getRelativePathFromURL('https://google.com/a/b/c')).toEqual('/a/b/c');