Skip to content

Commit

Permalink
fix: rule required options (#1000)
Browse files Browse the repository at this point in the history
  • Loading branch information
stone-jin authored Jun 10, 2021
1 parent 2bfc957 commit d76e9f7
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 4 deletions.
15 changes: 11 additions & 4 deletions packages/decorator/src/annotation/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,24 @@ import {
RULES_KEY,
} from '..';

export function Rule(rule) {
export interface RuleOptions {
required?: boolean;
}

export function Rule(rule, options: RuleOptions = { required: true }) {
return function (...args) {
if (args[1]) {
// 函数装饰器
const [target, propertyKey] = args;
if (!joi.isSchema(rule)) {
rule = getClassMetadata(RULES_KEY, rule);
if (getPropertyType(target, propertyKey)?.name === 'Array') {
rule = joi.array().items(rule).required();
if (getPropertyType(target, propertyKey).name === 'Array') {
rule = joi.array().items(rule);
} else {
rule = joi.object(rule).required();
rule = joi.object(rule);
}
if (options.required) {
rule = rule.required();
}
}

Expand Down
58 changes: 58 additions & 0 deletions packages/decorator/test/annotation/check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,64 @@ describe('/test/annotation/check.test.ts', () => {
assert.deepEqual(result, user);
});

it('check with check with options', () => {
class WorldDTO {
@Rule(RuleType.number().max(20))
age: number;
}

class UserDTO {
@Rule(RuleType.number().max(10))
age: number;

@Rule(WorldDTO, {required: false})
world?: WorldDTO;
}

class Hello {
@Validate()
school(a, data: UserDTO) {
return data;
}
}
const user = {
age: 10
};
const result = new Hello().school(1, user);
assert.deepEqual(result, user);
});

it('check with check with array', () => {
class WorldDTO {
@Rule(RuleType.number().max(20))
age: number;
}

class UserDTO {
@Rule(RuleType.number().max(10))
age: number;

@Rule(WorldDTO)
world: WorldDTO[];
}

class Hello {
@Validate()
school(a, data: UserDTO) {
return data;
}
}
const user = {
age: 10,
world: [{
age: 10
}, {
age: 22
}]
};
expect(()=> new Hello().school(1, user)).toThrow();
});

it('check with check and transform object', () => {
class UserDTO {
@Rule(RuleType.number().max(10))
Expand Down

0 comments on commit d76e9f7

Please sign in to comment.