Skip to content

Commit

Permalink
added throwif block
Browse files Browse the repository at this point in the history
  • Loading branch information
karmaniverous committed Jul 26, 2024
1 parent 2a0a385 commit a9aafc6
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <condition> <message>}}No Error!{{/throwif}}
```
1 change: 1 addition & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
14 changes: 14 additions & 0 deletions src/Handlebars.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!');
});
});
17 changes: 17 additions & 0 deletions src/Handlebars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

0 comments on commit a9aafc6

Please sign in to comment.