@jkcfg/std
Version:
jk standard library
59 lines (58 loc) • 1.9 kB
JavaScript
/**
* @module std/validation
*/
function isValidationError(err) {
return (typeof err === 'object' && 'msg' in err);
}
function normaliseError(err) {
if (typeof err === 'string')
return { msg: err };
if (typeof err === 'object' && isValidationError(err))
return err;
throw new Error(`unrecognised result from validation function: ${err}`);
}
// normaliseResult maps from the accepted return values of a
// validation function to the more restrictive `ValidateResult`, so
// that results can be dealt with uniformly.
export function normaliseResult(result) {
switch (typeof result) {
case 'string':
if (result === 'ok')
return result;
return [{ msg: result }];
case 'boolean':
if (result)
return 'ok';
return [{ msg: 'value not valid' }];
case 'object':
if (Array.isArray(result))
return result.map(normaliseError);
if (isValidationError(result))
return [result];
break;
default:
}
throw new Error(`unrecognised result from validation function: ${result}`);
}
/**
* formatError formats a validation error in a standard way. Since the
* errors do not include the source, this must be supplied.
*/
export function formatError(source, err) {
let out = err.msg;
if (err.path !== undefined) {
out = `${err.msg} at ${err.path}`;
}
if (err.start !== undefined) {
if (err.end !== undefined) {
out = `${err.start.line}.${err.start.column}-${err.end.line}.${err.end.column}: ${out}`;
}
else {
out = `${err.start.line}.${err.start.column}: ${out}`;
}
}
else { // if no location, put a spacer between the source file and message
out = ` ${out}`;
}
return `${source}:${out}`;
}