wip
This commit is contained in:
@ -2,7 +2,15 @@ import * as mongo from 'mongodb';
|
||||
|
||||
type Type = 'id' | 'string' | 'number' | 'boolean' | 'array' | 'object';
|
||||
|
||||
export default <T>(value: any, isRequired: boolean, type: Type, validator?: (any) => boolean): [T, string] => {
|
||||
type Validator<T> = ((x: T) => boolean | string) | ((x: T) => boolean | string)[];
|
||||
|
||||
function validate(value: any, type: 'id', isRequired?: boolean): [mongo.ObjectID, string];
|
||||
function validate(value: any, type: 'string', isRequired?: boolean, validator?: Validator<string>): [string, string];
|
||||
function validate(value: any, type: 'number', isRequired?: boolean, validator?: Validator<number>): [number, string];
|
||||
function validate(value: any, type: 'boolean', isRequired?: boolean): [boolean, string];
|
||||
function validate(value: any, type: 'array', isRequired?: boolean, validator?: Validator<any[]>): [any[], string];
|
||||
function validate(value: any, type: 'object', isRequired?: boolean, validator?: Validator<Object>): [Object, string];
|
||||
function validate<T>(value: any, type: Type, isRequired?: boolean, validator?: Validator<T>): [T, string] {
|
||||
if (value === undefined || value === null) {
|
||||
if (isRequired) {
|
||||
return [null, 'is-required']
|
||||
@ -49,11 +57,21 @@ export default <T>(value: any, isRequired: boolean, type: Type, validator?: (any
|
||||
break;
|
||||
}
|
||||
|
||||
if (type == 'id') value = new mongo.ObjectID(value);
|
||||
|
||||
if (validator) {
|
||||
if (!validator(value)) {
|
||||
return [null, 'invalid-format'];
|
||||
const validators = Array.isArray(validator) ? validator : [validator];
|
||||
for (let i = 0; i < validators.length; i++) {
|
||||
const result = validators[i](value);
|
||||
if (result === false) {
|
||||
return [null, 'invalid-format'];
|
||||
} else if (typeof result == 'string') {
|
||||
return [null, result];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [value, null];
|
||||
};
|
||||
}
|
||||
|
||||
export default validate;
|
||||
|
Reference in New Issue
Block a user