Skip to content

Commit 37833c2

Browse files
committed
fix(builder): fixed fluent api for the required rule builder
The required rule builder was in need of 2 optional parameters: path and errorMessage. However errorMessage can be specified regardless whether path is present or not, making the api cumbersome. Changed the builder adding the withPath, withErrorMessage and build methods BREAKING CHANGE: Now the required rule builder requires the build method to be called
1 parent 52a34bb commit 37833c2

File tree

2 files changed

+45
-7
lines changed

2 files changed

+45
-7
lines changed

src/example/nestedRulesSample-fluent.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@ const validator = validatorBuilder()
1616
.newRule()
1717
.withField('platform')
1818
.validate(RuleBuilder.isIn.withValues('MOBILE', 'DESKTOP').build())
19-
.validate(RuleBuilder.required())
19+
.validate(RuleBuilder.required.build())
2020
.newRule()
2121
.withFieldValueConstraint('platform', 'mobile')
2222
.withField('os')
2323
.validate(RuleBuilder.isIn.withValues('ANDROID', 'iOS', 'WINDOWS').build())
24-
.validate(RuleBuilder.required())
24+
.validate(RuleBuilder.required.build())
2525
.withField('programming_lang')
2626
.validate(
2727
RuleBuilder.composite
Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,47 @@
11
import {RuleConfig} from '../../config/RuleConfig';
22

3+
export interface RequiredRuleBuilder {
4+
withPath: (path: string) => RequiredRuleBuilder;
5+
withErrorMessage: (errorMessage: string) => RequiredRuleBuilder;
6+
build: () => RuleConfig;
7+
}
8+
9+
const createWithPath = (
10+
rule: RuleConfig
11+
): ((path: string) => RequiredRuleBuilder) => {
12+
const withPath = (path: string) => {
13+
rule.path = path;
14+
return {
15+
withPath: createWithPath(rule),
16+
withErrorMessage: createWithErrorMessage(rule),
17+
build: createBuild(rule),
18+
};
19+
};
20+
21+
return withPath;
22+
};
23+
24+
const createWithErrorMessage = (
25+
rule: RuleConfig
26+
): ((path: string) => RequiredRuleBuilder) => {
27+
const withErrorMessage = (errorMessage: string) => {
28+
rule.errorMessage = errorMessage;
29+
return {
30+
withPath: createWithPath(rule),
31+
withErrorMessage: createWithErrorMessage(rule),
32+
build: createBuild(rule),
33+
};
34+
};
35+
36+
return withErrorMessage;
37+
};
38+
39+
const createBuild = (rule: RuleConfig): (() => RuleConfig) => () => rule;
40+
341
export const builder = {
4-
required: (path?: string, errorMessage?: string): RuleConfig => ({
5-
type: 'REQUIRED',
6-
path,
7-
errorMessage,
8-
}),
42+
required: {
43+
withPath: createWithPath({type: 'REQUIRED'}),
44+
withErrorMessage: createWithErrorMessage({type: 'REQUIRED'}),
45+
build: createBuild({type: 'REQUIRED'}),
46+
},
947
};

0 commit comments

Comments
 (0)