-
Notifications
You must be signed in to change notification settings - Fork 934
/
Copy pathobject.js
269 lines (212 loc) · 6.86 KB
/
object.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import has from 'lodash/has';
import snakeCase from 'lodash/snakeCase';
import camelCase from 'lodash/camelCase';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
import { getter } from 'property-expr';
import MixedSchema from './mixed';
import { object as locale } from './locale.js';
import sortFields from './util/sortFields';
import sortByKeyOrder from './util/sortByKeyOrder';
import inherits from './util/inherits';
import makePath from './util/makePath';
import runValidations, { propagateErrors } from './util/runValidations';
let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
function unknown(ctx, value) {
let known = Object.keys(ctx.fields);
return Object.keys(value).filter(key => known.indexOf(key) === -1);
}
export default function ObjectSchema(spec) {
if (!(this instanceof ObjectSchema)) return new ObjectSchema(spec);
MixedSchema.call(this, {
type: 'object',
default() {
if (!this._nodes.length) return undefined;
let dft = {};
this._nodes.forEach(key => {
dft[key] = this.fields[key].default
? this.fields[key].default()
: undefined;
});
return dft;
},
});
this.fields = Object.create(null);
this._nodes = [];
this._excludedEdges = [];
this.withMutation(() => {
this.transform(function coerce(value) {
if (typeof value === 'string') {
try {
value = JSON.parse(value);
} catch (err) {
value = null;
}
}
if (this.isType(value)) return value;
return null;
});
if (spec) {
this.shape(spec);
}
});
}
inherits(ObjectSchema, MixedSchema, {
_typeCheck(value) {
return isObject(value) || typeof value === 'function';
},
_cast(_value, options = {}) {
let value = MixedSchema.prototype._cast.call(this, _value, options);
//should ignore nulls here
if (value === undefined) return this.default();
if (!this._typeCheck(value)) return value;
let fields = this.fields;
let strip = this._option('stripUnknown', options) === true;
let props = this._nodes.concat(
Object.keys(value).filter(v => this._nodes.indexOf(v) === -1),
);
let intermediateValue = {}; // is filled during the transform below
let innerOptions = {
...options,
parent: intermediateValue,
__validating: false,
};
let isChanged = false;
props.forEach(prop => {
let field = fields[prop];
let exists = has(value, prop);
if (field) {
let fieldValue;
let strict = field._options && field._options.strict;
// safe to mutate since this is fired in sequence
innerOptions.path = makePath`${options.path}.${prop}`;
innerOptions.value = value[prop];
field = field.resolve(innerOptions);
if (field._strip === true) {
isChanged = isChanged || prop in value;
return;
}
fieldValue =
!options.__validating || !strict
? field.cast(value[prop], innerOptions)
: value[prop];
if (fieldValue !== undefined) intermediateValue[prop] = fieldValue;
} else if (exists && !strip) intermediateValue[prop] = value[prop];
if (intermediateValue[prop] !== value[prop]) isChanged = true;
});
return isChanged ? intermediateValue : value;
},
_validate(_value, opts = {}) {
let endEarly, recursive;
let sync = opts.sync;
let errors = [];
let originalValue =
opts.originalValue != null ? opts.originalValue : _value;
endEarly = this._option('abortEarly', opts);
recursive = this._option('recursive', opts);
opts = { ...opts, __validating: true, originalValue };
return MixedSchema.prototype._validate
.call(this, _value, opts)
.catch(propagateErrors(endEarly, errors))
.then(value => {
if (!recursive || !isObject(value)) {
// only iterate though actual objects
if (errors.length) throw errors[0];
return value;
}
originalValue = originalValue || value;
let validations = this._nodes.map(key => {
let path = makePath`${opts.path}.${key}`;
let field = this.fields[key];
let innerOptions = {
...opts,
path,
parent: value,
originalValue: originalValue[key],
};
if (field && field.validate) {
// inner fields are always strict:
// 1. this isn't strict so the casting will also have cast inner values
// 2. this is strict in which case the nested values weren't cast either
innerOptions.strict = true;
return field.validate(value[key], innerOptions);
}
return Promise.resolve(true);
});
return runValidations({
sync,
validations,
value,
errors,
endEarly,
path: opts.path,
sort: sortByKeyOrder(this.fields),
});
});
},
concat(schema) {
var next = MixedSchema.prototype.concat.call(this, schema);
next._nodes = sortFields(next.fields, next._excludedEdges);
return next;
},
shape(schema, excludes = []) {
let next = this.clone();
let fields = Object.assign(next.fields, schema);
next.fields = fields;
if (excludes.length) {
if (!Array.isArray(excludes[0])) excludes = [excludes];
let keys = excludes.map(([first, second]) => `${first}-${second}`);
next._excludedEdges = next._excludedEdges.concat(keys);
}
next._nodes = sortFields(fields, next._excludedEdges);
return next;
},
from(from, to, alias) {
let fromGetter = getter(from, true);
return this.transform(obj => {
if (obj == null) return obj;
let newObj = obj;
if (has(obj, from)) {
newObj = { ...obj };
if (!alias) delete newObj[from];
newObj[to] = fromGetter(obj);
}
return newObj;
});
},
noUnknown(noAllow = true, message = locale.noUnknown) {
if (typeof noAllow === 'string') {
message = noAllow;
noAllow = true;
}
let next = this.test({
name: 'noUnknown',
exclusive: true,
message: message,
test(value) {
return (
value == null || !noAllow || unknown(this.schema, value).length === 0
);
},
});
if (noAllow) next._options.stripUnknown = true;
return next;
},
transformKeys(fn) {
return this.transform(obj => obj && mapKeys(obj, (_, key) => fn(key)));
},
camelCase() {
return this.transformKeys(camelCase);
},
snakeCase() {
return this.transformKeys(snakeCase);
},
constantCase() {
return this.transformKeys(key => snakeCase(key).toUpperCase());
},
describe() {
let base = MixedSchema.prototype.describe.call(this);
base.fields = mapValues(this.fields, value => value.describe());
return base;
},
});