Permalink
Show file tree
Hide file tree
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Showing
3 changed files
with
90 additions
and
47 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// 定义一个私有 key | ||
const requiredMetadataKey = Symbol.for('router:required') | ||
|
||
// 定义参数装饰器,大概思路就是把要校验的参数索引保存到成员中 | ||
export const required = function (target, propertyKey: string, parameterIndex: number) { | ||
// 属性附加 | ||
const rules = Reflect.getMetadata(requiredMetadataKey, target, propertyKey) || [] | ||
rules.push(parameterIndex) | ||
Reflect.defineMetadata(requiredMetadataKey, rules, target, propertyKey) | ||
} | ||
|
||
// 定义一个方法装饰器,从成员中获取要校验的参数进行校验 | ||
export const validateEmptyStr = function (target, propertyKey: string, descriptor: PropertyDescriptor) { | ||
// 保存原来的方法 | ||
let method = descriptor.value | ||
// 重写原来的方法 | ||
descriptor.value = function () { | ||
let args = arguments | ||
// 看看成员里面有没有存的私有的对象 | ||
const rules = Reflect.getMetadata(requiredMetadataKey, target, propertyKey) as Array<number> | ||
if (rules && rules.length) { | ||
// 检查私有对象的 key | ||
rules.forEach(parameterIndex => { | ||
// 对应索引的参数进行校验 | ||
if (!args[parameterIndex]) throw Error(`arguments${parameterIndex} is invalid`) | ||
}) | ||
} | ||
return method.apply(this, arguments) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters