Skip to content

Commit

Permalink
feat: add useCache validation option
Browse files Browse the repository at this point in the history
  • Loading branch information
William17 committed Aug 28, 2018
1 parent df7def8 commit 90e1c36
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 7 deletions.
3 changes: 3 additions & 0 deletions src/interface/index.ts
Expand Up @@ -180,6 +180,7 @@ export interface ValidationOptions {
removeAdditional?: boolean;
skipAsync?: boolean;
skips?: string[];
useCache?: boolean;
}

export interface GateSchemaBase {
Expand Down Expand Up @@ -254,6 +255,8 @@ export interface GateSchemaKeywords {
| [number, number]
): GateSchema;
notEmpty: GateSchema;
max(value: number, isExclusive?: boolean): GateSchema;
min(value: number, isExclusive?: boolean): GateSchema;
pattern(regex: string | RegExp, flags?: string): GateSchema;
unique: GateSchema;

Expand Down
4 changes: 4 additions & 0 deletions src/msgs.ts
Expand Up @@ -25,6 +25,10 @@ export default {
length_binary_min: 'should contain at least ${minLength} bytes',
length_binary_max: 'should contain at most ${maxLength} bytes',
length_binary_range: 'should contain ${minLength} to ${maxLength} bytes',
max: 'should be less than or equal to ${max}',
max_exclusive: 'should be less than ${max}',
min: 'should be greater than or equal to ${min}',
min_exclusive: 'should be greater than ${min}',
notEmpty: 'should not be empty',
oneOf: 'invalid value',
pattern: 'invalid format',
Expand Down
21 changes: 14 additions & 7 deletions src/schemaBase.ts
Expand Up @@ -399,16 +399,25 @@ class GateSchema implements I.GateSchemaBase {
{ path, rootData, schema, state, options = {} }: I.SchemaValidationCtx,
cb: I.ValidationCallback
) {
const resultCache = getCacheResult(path, schema, state);
if (resultCache) {
return cb(resultCache);
}
const { _validators, BREAK, Error: VError, _asyncKeywords } = this;
const {
removeAdditional: REMOVE_ADDITIONAL,
skips: SKIPS,
skipAsync: SKIP_ASYNC
skipAsync: SKIP_ASYNC,
useCache: USE_CACHE
} = options;
if (USE_CACHE) {
const resultCache = getCacheResult(path, schema, state);
if (resultCache) {
return cb(resultCache);
}

const originCb = cb;
cb = (err: any) => {
appendCacheResult(err, path, schema, state);
originCb(err);
};
}
const constraints = getConstraints(schema);
const constraintsLength = constraints.length;
let i = 0;
Expand Down Expand Up @@ -442,7 +451,6 @@ class GateSchema implements I.GateSchemaBase {
state
});
}
appendCacheResult(result, path, schema, state);
cb(result);
} else if (i < constraintsLength) {
item = constraints[i++];
Expand Down Expand Up @@ -481,7 +489,6 @@ class GateSchema implements I.GateSchemaBase {
);
}
} else {
appendCacheResult(null, path, schema, state);
if (REMOVE_ADDITIONAL) {
removeAdditional(path, state);
}
Expand Down

0 comments on commit 90e1c36

Please sign in to comment.