Skip to content
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

feat: addAsyncRule to allow sync and async rules to run #63

Merged
merged 5 commits into from
Mar 2, 2023
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ function asyncCheckEmail(email) {
const model = SchemaModel({
email: StringType()
.isEmail('Please input the correct email address')
.addRule((value, data) => {
.addAsyncRule((value, data) => {
return asyncCheckEmail(value);
}, 'Email address already exists')
.isRequired('This field cannot be empty')
Expand Down Expand Up @@ -391,7 +391,7 @@ Asynchronously check whether a field in the data conforms to the model shape def
const model = SchemaModel({
username: StringType()
.isRequired('This field required')
.addRule(value => {
.addAsyncRule(value => {
return new Promise(resolve => {
// Asynchronous processing logic
});
Expand Down
11 changes: 10 additions & 1 deletion src/MixedType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
SchemaDeclaration,
CheckResult,
ValidCallbackType,
AsyncValidCallbackType,
RuleType,
ErrorMessageType,
TypeName
Expand Down Expand Up @@ -101,6 +102,7 @@ export class MixedType<ValueType = any, DataType = any, E = ErrorMessageType, L
const nextRule = {
onValid,
params,
isAsync: rule.isAsync,
errorMessage: errorMessage || this.rules?.[0]?.errorMessage
};

Expand All @@ -118,7 +120,14 @@ export class MixedType<ValueType = any, DataType = any, E = ErrorMessageType, L
this.pushRule({ onValid, errorMessage, priority });
return this;
}

addAsyncRule(
onValid: AsyncValidCallbackType<ValueType, DataType, E | string>,
errorMessage?: E | string,
priority?: boolean
) {
this.pushRule({ onValid, isAsync: true, errorMessage, priority });
return this;
}
isRequired(errorMessage: E | string = this.locale.isRequired, trim = true) {
this.required = true;
this.trim = trim;
Expand Down
10 changes: 9 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,24 @@ export type ValidCallbackType<V, D, E> = (
value: V,
data?: D,
filedName?: string | string[]
) => CheckResult<E> | boolean;

export type AsyncValidCallbackType<V, D, E> = (
value: V,
data?: D,
filedName?: string | string[]
) => CheckResult<E> | boolean | Promise<boolean | CheckResult<E>>;

export type PlainObject<T extends Record<string, unknown> = any> = {
[P in keyof T]: T;
};

export interface RuleType<V, D, E> {
onValid: ValidCallbackType<V, D, E>;
onValid: AsyncValidCallbackType<V, D, E>;
errorMessage?: E;
priority?: boolean;
params?: any;
isAsync?: boolean;
}

export type CheckType<X, T, E = ErrorMessageType> = X extends string
Expand Down
3 changes: 2 additions & 1 deletion src/utils/createValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ function isPromiseLike(v: unknown): v is Promise<unknown> {
export function createValidator<V, D, E>(data?: D, name?: string | string[]) {
return (value: V, rules: RuleType<V, D, E>[]): CheckResult<E> | null => {
for (let i = 0; i < rules.length; i += 1) {
const { onValid, errorMessage, params } = rules[i];
const { onValid, errorMessage, params, isAsync } = rules[i];
if (isAsync) continue;
const checkResult = onValid(value, data, name);

if (checkResult === false) {
Expand Down
44 changes: 44 additions & 0 deletions test/MixedTypeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -416,4 +416,48 @@ describe('#MixedType', () => {
.expect(err?.message)
.to.eql('synchronous validator had an async result, you should probably call "checkAsync()"');
});
it('Should be able to check by `checkAsync` with `addAsyncRule`', done => {
const type = MixedType()
.addAsyncRule(v => {
return new Promise(resolve => {
setTimeout(() => {
if (typeof v === 'number') {
resolve(true);
} else {
resolve(false);
}
}, 500);
});
}, 'error1')
.isRequired('error2');

Promise.all([type.checkAsync(''), type.checkAsync('1'), type.checkAsync(1)]).then(res => {
if (res[0].hasError && res[1].hasError && !res[2].hasError) {
done();
}
});
});
it('Should be able to check by `check` with `addAsyncRule` and skip the async ', done => {
let called = false;
const type = MixedType()
.addRule(v => {
return typeof v === 'number';
}, 'This is not async')
.addAsyncRule(async () => {
called = true;
return false;
}, 'error1')
.isRequired('error2');
setTimeout(() => {
try {
chai.expect(called).to.eq(false);
chai.expect(type.check('').hasError).to.eq(true);
chai.expect(type.check('1').hasError).to.eq(true);
chai.expect(type.check(1).hasError).to.eq(false);
done();
} catch (e) {
done(e);
}
}, 100);
});
});