Skip to content

WIP Solution for #94 #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions plugins/Validation/src/Validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,14 @@ export interface ValidationError {
readonly severity: ValidationSeverity;
}

type ValidationExtensionValidate<S> = {
(attachRule: (value: S) => boolean,
message: string | ((value: S) => string),
severity?: ValidationSeverity): void
}

export interface ValidationExtensions<S> {
validate(attachRule: (value: S) => boolean,
message: string | ((value: S) => string),
severity?: ValidationSeverity): void,
validate: ValidationExtensionValidate<S>,
validShallow(): boolean,
valid(): boolean,
invalidShallow(): boolean,
Expand All @@ -28,6 +32,10 @@ export interface ValidationExtensions<S> {
): ReadonlyArray<ValidationError>,
}

export interface ValidationExtensionsArray<S, U> extends ValidationExtensions<S> {
forEach: ValidationExtensionValidate<U>
}

const PluginID = Symbol('Validate');

const emptyErrors: ValidationError[] = []
Expand Down Expand Up @@ -170,10 +178,17 @@ class ValidationPluginInstance<S> {
}
}

type ValidationExtensionsSubtype<S> = (S extends ReadonlyArray<(infer U)> ? ValidationExtensionsArray<S, U> : ValidationExtensions<S>);

// tslint:disable-next-line: no-any
function isArray<U>(state: any): state is ReadonlyArray<U> {
return state.keys && typeof state.keys[0] === 'number';
}

// tslint:disable-next-line: function-name
export function Validation(): Plugin;
export function Validation<S>($this: State<S>): ValidationExtensions<S>;
export function Validation<S>($this?: State<S>): Plugin | ValidationExtensions<S> {
export function Validation<S>($this: State<S>): ValidationExtensionsSubtype<S>;
export function Validation<S>($this?: State<S>): Plugin | ValidationExtensionsSubtype<S> {
if ($this) {
let state = $this;

Expand All @@ -185,6 +200,13 @@ export function Validation<S>($this?: State<S>): Plugin | ValidationExtensions<S

const inst = instance;
return {
forEach: (r, m, s) => {
inst.addRule(state[0], {
rule: r,
message: m,
severity: s || 'error'
})
},
validate: (r, m, s) => {
inst.addRule(state.path, {
rule: r,
Expand Down Expand Up @@ -213,7 +235,7 @@ export function Validation<S>($this?: State<S>): Plugin | ValidationExtensions<S
return {};
}
return r[0];
},
}
}
}
return {
Expand Down