Skip to content

Commit

Permalink
feat: Add JSONparseSafe helper (#235)
Browse files Browse the repository at this point in the history
* feat: Add JSONparseSafe helper

* feat: Update tests
  • Loading branch information
RomanKrasinskyi authored Feb 2, 2023
1 parent c83bb31 commit f9edc1b
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const helpersList = [
'join',
'jsContext',
'json',
'jsonParseSafe',
'lang',
'langJson',
'limit',
Expand Down
18 changes: 18 additions & 0 deletions helpers/jsonParseSafe.js
Original file line number Diff line number Diff line change
@@ -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,
}];
1 change: 1 addition & 0 deletions spec/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ describe('helper registration', () => {
'hasOwn',
'isObject',
'merge',
'JSONparseSafe',
'JSONparse',
'JSONstringify',
'camelcase',
Expand Down
38 changes: 38 additions & 0 deletions spec/helpers/jsonParseSafe.js
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit f9edc1b

Please sign in to comment.