-
Notifications
You must be signed in to change notification settings - Fork 936
/
Reference.ts
94 lines (72 loc) · 2.18 KB
/
Reference.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { getter } from 'property-expr';
import type { SchemaRefDescription } from './schema';
const prefixes = {
context: '$',
value: '.',
} as const;
export type ReferenceOptions<TValue = unknown> = {
map?: (value: unknown) => TValue;
};
export function create(key: string, options?: ReferenceOptions) {
return new Reference(key, options);
}
export default class Reference<TValue = unknown> {
readonly key: string;
readonly isContext: boolean;
readonly isValue: boolean;
readonly isSibling: boolean;
readonly path: any;
readonly getter: (data: unknown) => unknown;
readonly map?: (value: unknown) => TValue;
readonly __isYupRef!: boolean;
constructor(key: string, options: ReferenceOptions<TValue> = {}) {
if (typeof key !== 'string')
throw new TypeError('ref must be a string, got: ' + key);
this.key = key.trim();
if (key === '') throw new TypeError('ref must be a non-empty string');
this.isContext = this.key[0] === prefixes.context;
this.isValue = this.key[0] === prefixes.value;
this.isSibling = !this.isContext && !this.isValue;
let prefix = this.isContext
? prefixes.context
: this.isValue
? prefixes.value
: '';
this.path = this.key.slice(prefix.length);
this.getter = this.path && getter(this.path, true);
this.map = options.map;
}
getValue(value: any, parent?: {}, context?: {}): TValue {
let result = this.isContext ? context : this.isValue ? value : parent;
if (this.getter) result = this.getter(result || {});
if (this.map) result = this.map(result);
return result;
}
/**
*
* @param {*} value
* @param {Object} options
* @param {Object=} options.context
* @param {Object=} options.parent
*/
cast(value: any, options?: { parent?: {}; context?: {} }) {
return this.getValue(value, options?.parent, options?.context);
}
resolve() {
return this;
}
describe(): SchemaRefDescription {
return {
type: 'ref',
key: this.key,
};
}
toString() {
return `Ref(${this.key})`;
}
static isRef(value: any): value is Reference {
return value && value.__isYupRef;
}
}
// @ts-ignore
Reference.prototype.__isYupRef = true;