From a9aafc606225af721648b278c3e01864fd537537 Mon Sep 17 00:00:00 2001 From: Jason Williscroft Date: Fri, 26 Jul 2024 11:24:10 +0800 Subject: [PATCH] added throwif block --- README.md | 8 ++++++++ eslint.config.js | 1 + src/Handlebars.test.ts | 14 ++++++++++++++ src/Handlebars.ts | 17 +++++++++++++++++ 4 files changed, 40 insertions(+) diff --git a/README.md b/README.md index 7053f4e..3ef4eef 100644 --- a/README.md +++ b/README.md @@ -150,3 +150,11 @@ These targets are currently available: | `target` | Description | default `delimiter` | | -------- | ----------------------------------------------------------------------------------------------- | ------------------- | | `s3` | [S3 bucket names](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) | `'-'` | + +## throwif + +Checks an condition. If true, throws an error before evauating the block content. Syntax: + +```handlebars +{{#throwif }}No Error!{{/throwif}} +``` diff --git a/eslint.config.js b/eslint.config.js index 0892b72..b835ecb 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -25,6 +25,7 @@ export default tseslint.config( tsdoc: tsDocPlugin, }, rules: { + '@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/no-unused-vars': 'error', 'mocha/no-skipped-tests': 'off', 'mocha/no-top-level-hooks': 'off', diff --git a/src/Handlebars.test.ts b/src/Handlebars.test.ts index 281645c..48657ef 100644 --- a/src/Handlebars.test.ts +++ b/src/Handlebars.test.ts @@ -141,4 +141,18 @@ describe('Handlebars', function () { expect(result).to.equal('metastructure-001-shared-services-s3-access-log'); }); + + it('throwif true', function () { + const template = '{{#throwif amount "Error!"}}No Error!{{/throwif}}'; + + expect(() => Handlebars.compile(template)(data)).to.throw('Error!'); + }); + + it('throwif false', function () { + const template = '{{#throwif falsy "Error!"}}No Error!{{/throwif}}'; + + const result = Handlebars.compile(template)(data); + + expect(result).to.equal('No Error!'); + }); }); diff --git a/src/Handlebars.ts b/src/Handlebars.ts index cf8c1cc..041178f 100644 --- a/src/Handlebars.ts +++ b/src/Handlebars.ts @@ -117,4 +117,21 @@ Handlebars.registerHelper( }, ); +Handlebars.registerHelper( + 'throwif', + function ( + condition: boolean, + messageParam: string | Handlebars.HelperOptions, + optionsParam?: Handlebars.HelperOptions, + ) { + const message = _.isString(messageParam) ? messageParam : undefined; + const options = (_.isString(messageParam) ? optionsParam : messageParam)!; + + if (condition) throw new Error(message); + + // @ts-expect-error 'this' implicitly has type 'any' because it does not have a type annotation. + return options.fn(this); + }, +); + export { Handlebars };