mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-20 01:38:19 +08:00
framework: add support for passing schemastery as validator
This commit is contained in:
3 files changed
+63
-22
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { Context } from 'cordis';
|
||||
import Schema from 'schemastery';
|
||||
import { ValidationError } from './error';
|
||||
import type { Handler } from './server';
|
||||
import { Converter, Type, Validator } from './validator';
|
||||
@@ -14,14 +15,32 @@ export interface ParamOption<T> {
|
||||
validate?: Validator,
|
||||
}
|
||||
|
||||
const kSchema = Symbol.for('schemastery');
|
||||
const mergeValidator = (L: Validator, R: Validator) => (v: any) => L(v) && R(v);
|
||||
|
||||
function isSchema(v: any): v is Schema {
|
||||
return v && typeof v === 'function' && kSchema in v;
|
||||
}
|
||||
|
||||
function _buildParam(name: string, source: 'get' | 'post' | 'all' | 'route', ...args: Array<Type<any> | boolean | Validator | Converter<any>>) {
|
||||
let cursor = 0;
|
||||
const v: ParamOption<any> = { name, source };
|
||||
let isValidate = true;
|
||||
while (cursor < args.length) {
|
||||
const current = args[cursor];
|
||||
if (isSchema(current)) {
|
||||
v.validate = (val) => {
|
||||
try {
|
||||
current(val);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
v.convert = (val) => current(val);
|
||||
cursor++;
|
||||
continue;
|
||||
}
|
||||
if (current instanceof Array) {
|
||||
const type = current;
|
||||
if (type[0]) v.convert = type[0];
|
||||
|
||||
Reference in new issue
Block a user