-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #19 from harrygr/flexible-data
feat: Allow any data to be validated by a given validator
- Loading branch information
Showing
2 changed files
with
37 additions
and
32 deletions.
There are no files selected for viewing
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
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 |
---|---|---|
@@ -1,38 +1,27 @@ | ||
export type Constraint<F extends object, T = any> = ( | ||
val: T, | ||
fields: F, | ||
) => string | undefined | ||
export type Constraints<F extends object> = Partial< | ||
Record<keyof F, Constraint<F>[]> | ||
> | ||
export type ValidationResult<F extends object> = Partial< | ||
Record<keyof F, string | undefined> | ||
export type Rule<D extends object> = (val: any, fields: D) => string | undefined | ||
|
||
export type RuleSet<R extends object, D extends object> = Record< | ||
keyof R, | ||
Rule<D>[] | ||
> | ||
|
||
export const makeValidator = <F extends object>( | ||
constraints: Constraints<F>, | ||
export const makeValidator = <D extends object, R extends object = Partial<D>>( | ||
ruleSet: RuleSet<R, D>, | ||
) => { | ||
return (fields: F): ValidationResult<F> => { | ||
const fieldNames = Object.keys(fields) as (keyof F)[] | ||
const fieldnamesToValidate = Object.keys(ruleSet) | ||
|
||
const getErrors = ( | ||
errors: ValidationResult<F>, | ||
fieldName: keyof F, | ||
): ValidationResult<F> => { | ||
const val = fields[fieldName] | ||
const fieldConstraints = (constraints[fieldName] || []) as Constraint< | ||
F, | ||
typeof val | ||
>[] | ||
return (data: D) => { | ||
return fieldnamesToValidate.reduce((acc, field) => { | ||
const rules = ruleSet[field] as Rule<D>[] | ||
|
||
const error = fieldConstraints.reduce( | ||
(err, con) => (err ? err : con(val, fields)), | ||
const valueToValidate = data[field] | ||
|
||
const error = rules.reduce( | ||
(err, v) => (err ? err : v(valueToValidate, data)), | ||
undefined, | ||
) | ||
|
||
return error ? { ...errors, [fieldName]: error } : errors | ||
} | ||
|
||
return fieldNames.reduce(getErrors, {} as ValidationResult<F>) | ||
return error ? { ...acc, [field]: error } : acc | ||
}, {} as Record<keyof R, string>) | ||
} | ||
} |