/
errors.ts
52 lines (43 loc) · 1.36 KB
/
errors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk from 'chalk';
import getType from 'jest-get-type';
import {formatPrettyObject, ValidationError, ERROR} from './utils';
import {getValues} from './condition';
import {ValidationOptions} from './types';
export const errorMessage = (
option: string,
received: any,
defaultValue: any,
options: ValidationOptions,
path?: Array<string>,
): void => {
const conditions = getValues(defaultValue);
const validTypes: Array<string> = Array.from(
new Set(conditions.map(getType)),
);
const message = ` Option ${chalk.bold(
`"${path && path.length > 0 ? path.join('.') + '.' : ''}${option}"`,
)} must be of type:
${validTypes.map(e => chalk.bold.green(e)).join(' or ')}
but instead received:
${chalk.bold.red(getType(received))}
Example:
${formatExamples(option, conditions)}`;
const comment = options.comment;
const name = (options.title && options.title.error) || ERROR;
throw new ValidationError(name, message, comment);
};
function formatExamples(option: string, examples: Array<any>) {
return examples.map(
e => ` {
${chalk.bold(`"${option}"`)}: ${chalk.bold(formatPrettyObject(e))}
}`,
).join(`
or
`);
}