-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathenum.js
More file actions
74 lines (62 loc) Β· 1.77 KB
/
enum.js
File metadata and controls
74 lines (62 loc) Β· 1.77 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import chalk from 'chalk';
import leven from 'leven';
import pointer from 'jsonpointer';
import BaseValidationError from './base';
export default class EnumValidationError extends BaseValidationError {
print() {
const {
message,
params: { allowedValues },
} = this.options;
const bestMatch = this.findBestMatch();
const output = [
chalk`{red {bold ENUM} ${message}}`,
chalk`{red (${allowedValues.join(', ')})}\n`,
];
return output.concat(
this.getCodeFrame(
bestMatch !== null
? chalk`ππ½ Did you mean {magentaBright ${bestMatch}} here?`
: chalk`ππ½ Unexpected value, should be equal to one of the allowed values`
)
);
}
getError() {
const { message, params } = this.options;
const bestMatch = this.findBestMatch();
const allowedValues = params.allowedValues.join(', ');
const output = {
...this.getLocation(),
error: `${this.getDecoratedPath()} ${message}: ${allowedValues}`,
path: this.instancePath,
};
if (bestMatch !== null) {
output.suggestion = `Did you mean ${bestMatch}?`;
}
return output;
}
findBestMatch() {
const {
params: { allowedValues },
} = this.options;
const currentValue =
this.instancePath === ''
? this.data
: pointer.get(this.data, this.instancePath);
if (!currentValue) {
return null;
}
const bestMatch = allowedValues
.map(value => ({
value,
weight: leven(value, currentValue.toString()),
}))
.sort((x, y) =>
x.weight > y.weight ? 1 : x.weight < y.weight ? -1 : 0
)[0];
return allowedValues.length === 1 ||
bestMatch.weight < bestMatch.value.length
? bestMatch.value
: null;
}
}