Skip to content
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
7 changes: 7 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -783,7 +783,14 @@ Adds an external validation rule where:
return a replacement value, `undefined` to indicate no change, or throw an error, where:
- `value` - a clone of the object containing the value being validated.
- `helpers` - an object with the following helpers:
- `schema` - the current schema.
- `linked` - if the schema is a link, the schema it links to.
- `state` - the current validation state.
- `prefs` - the current preferences.
- `original` - the original value passed into validation before any conversions.
- `error(code, [local])` - a method to generate error codes using a message code and optional local context.
- `message(messages, [local])` - a method to generate an error with an internal `'external'` error code and the provided messages object to use as override. Note that this is much slower than using the preferences `messages` option but is much simpler to write when performance is not important.
- `warn(code, [local])` - a method to add a warning using a message code and optional local context.
- `description` - optional string used to document the purpose of the method.

Note that external validation rules are only called after the all other validation rules for the
Expand Down
13 changes: 10 additions & 3 deletions lib/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -742,13 +742,20 @@ declare namespace Joi {
message: (messages: LanguageMessages, local?: Context) => ErrorReport;
}

type CustomValidator<V = any> = (value: V, helpers: CustomHelpers) => V | ErrorReport;
type CustomValidator<V = any, R = V> = (value: V, helpers: CustomHelpers<R>) => R | ErrorReport;

interface ExternalHelpers {
interface ExternalHelpers<V = any> {
schema: ExtensionBoundSchema;
linked: ExtensionBoundSchema | null;
state: State;
prefs: ValidationOptions;
original: V;
warn: (code: string, local?: Context) => void;
error: (code: string, local?: Context) => ErrorReport;
message: (messages: LanguageMessages, local?: Context) => ErrorReport;
}

type ExternalValidationFunction<V = any> = (value: V, helpers: ExternalHelpers) => V | undefined;
type ExternalValidationFunction<V = any, R = V> = (value: V, helpers: ExternalHelpers<R>) => R | undefined;

type SchemaLikeWithoutArray = string | number | boolean | null | Schema | SchemaMap;
type SchemaLike = SchemaLikeWithoutArray | object;
Expand Down
70 changes: 65 additions & 5 deletions lib/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,42 +67,102 @@ exports.entryAsync = async function (value, schema, prefs) {

if (mainstay.externals.length) {
let root = result.value;
for (const { method, path, label } of mainstay.externals) {
const errors = [];
for (const external of mainstay.externals) {
const path = external.state.path;
const linked = external.schema.type === 'link' ? mainstay.links.get(external.schema) : null;
let node = root;
let key;
let parent;

const ancestors = path.length ? [root] : [];
const original = path.length ? Reach(value, path) : value;

if (path.length) {
key = path[path.length - 1];
parent = Reach(root, path.slice(0, -1));

let current = root;
for (const segment of path.slice(0, -1)) {
current = current[segment];
ancestors.unshift(current);
}

parent = ancestors[0];
node = parent[key];
}

try {
const output = await method(node, { prefs });
const createError = (code, local) => (linked || external.schema).$_createError(code, node, local, external.state, settings);
const output = await external.method(node, {
schema: external.schema,
linked,
state: external.state,
prefs,
original,
error: createError,
errorsArray: internals.errorsArray,
warn: (code, local) => mainstay.warnings.push((linked || external.schema).$_createError(code, node, local, external.state, settings)),
message: (messages, local) => (linked || external.schema).$_createError('external', node, local, external.state, settings, { messages })
});

if (output === undefined ||
output === node) {

continue;
}

if (output instanceof Errors.Report) {
mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error');
errors.push(output);

if (settings.abortEarly) {
break;
}

continue;
}

if (Array.isArray(output) &&
output[Common.symbols.errors]) {
mainstay.tracer.log(external.schema, external.state, 'rule', 'external', 'error');
errors.push(...output);

if (settings.abortEarly) {
break;
}

continue;
}

if (parent) {
mainstay.tracer.value(external.state, 'rule', node, output, 'external');
parent[key] = output;
}
else {
mainstay.tracer.value(external.state, 'rule', root, output, 'external');
root = output;
}
}
catch (err) {
if (settings.errors.label) {
err.message += ` (${label})`; // Change message to include path
err.message += ` (${(external.label)})`; // Change message to include path
}

throw err;
}
}

result.value = root;

if (errors.length) {
result.error = Errors.process(errors, value, settings);

if (mainstay.debug) {
result.error.debug = mainstay.debug;
}

throw result.error;
}
}

if (!settings.warnings &&
Expand Down Expand Up @@ -514,7 +574,7 @@ internals.finalize = function (value, errors, helpers) {
prefs._externals !== false) { // Disabled for matching

for (const { method } of schema.$_terms.externals) {
state.mainstay.externals.push({ method, path: state.path, label: Errors.label(schema._flags, state, prefs) });
state.mainstay.externals.push({ method, schema, state, label: Errors.label(schema._flags, state, prefs) });
}
}

Expand Down
Loading