From f9edc1b11c05a84eb159a08681910fcad8c01410 Mon Sep 17 00:00:00 2001 From: Roman Krasinskyi <49246595+RomanKrasinskyi@users.noreply.github.com> Date: Thu, 2 Feb 2023 18:36:25 +0200 Subject: [PATCH] feat: Add JSONparseSafe helper (#235) * feat: Add JSONparseSafe helper * feat: Update tests --- helpers.js | 1 + helpers/jsonParseSafe.js | 18 +++++++++++++++++ spec/helpers.js | 1 + spec/helpers/jsonParseSafe.js | 38 +++++++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+) create mode 100644 helpers/jsonParseSafe.js create mode 100644 spec/helpers/jsonParseSafe.js diff --git a/helpers.js b/helpers.js index 9f78ec6..c764cce 100644 --- a/helpers.js +++ b/helpers.js @@ -30,6 +30,7 @@ const helpersList = [ 'join', 'jsContext', 'json', + 'jsonParseSafe', 'lang', 'langJson', 'limit', diff --git a/helpers/jsonParseSafe.js b/helpers/jsonParseSafe.js new file mode 100644 index 0000000..0cb6c74 --- /dev/null +++ b/helpers/jsonParseSafe.js @@ -0,0 +1,18 @@ +'use strict'; + +function factory(globals) { + return function (value) { + const options = arguments[arguments.length - 1]; + + try { + return options.fn(JSON.parse(value)); + } catch (err) { + return options.inverse(this); + } + }; +} + +module.exports = [{ + name: 'JSONparseSafe', + factory: factory, +}]; diff --git a/spec/helpers.js b/spec/helpers.js index 337f55d..221feaf 100644 --- a/spec/helpers.js +++ b/spec/helpers.js @@ -146,6 +146,7 @@ describe('helper registration', () => { 'hasOwn', 'isObject', 'merge', + 'JSONparseSafe', 'JSONparse', 'JSONstringify', 'camelcase', diff --git a/spec/helpers/jsonParseSafe.js b/spec/helpers/jsonParseSafe.js new file mode 100644 index 0000000..59f88d3 --- /dev/null +++ b/spec/helpers/jsonParseSafe.js @@ -0,0 +1,38 @@ +const { describe, it } = exports.lab = require('lab').script(); + +const { testRunner } = require('../spec-helpers'); + +describe('JSONParseSafe helper', () => { + const context = { + jsonString: '{"name": "John"}', + string: 'John Doe', + }; + const runTestCases = testRunner({context}); + + it('should execute the main instruction', done => { + runTestCases([ + { + input: '{{#JSONparseSafe jsonString}}{{name}}{{/JSONparseSafe}}', + output: 'John', + }, + ], done); + }); + + it('should skip the main instruction if variable is non-json', done => { + runTestCases([ + { + input: '{{#JSONparseSafe string}}{{name}}{{/JSONparseSafe}}', + output: '', + }, + ], done); + }); + + it('should execute the else instruction if variable is non-json', done => { + runTestCases([ + { + input: '{{#JSONparseSafe string}}{{name}}{{else}}{{string}}{{/JSONparseSafe}}', + output: 'John Doe', + }, + ], done); + }); +});