-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
executable file
·74 lines (57 loc) · 2.23 KB
/
index.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
import { PropTypes } from 'prop-types';
function hasPropTypes(obj) {
return typeof obj.propTypes === 'object';
}
function hasDefaultProps(obj) {
return typeof obj.defaultProps === 'object';
}
export function getPropTypesMixin(userOpts) {
const opts = userOpts || {};
let useValidation;
if (Object.prototype.hasOwnProperty.call(opts, 'validate')) {
useValidation = opts.validate;
} else if (process) {
useValidation = process.env.NODE_ENV !== 'production';
} else {
useValidation = true;
}
const useDefaults = Object.prototype.hasOwnProperty.call(opts, 'useDefaults')
? opts.useDefaults
: true;
return superclass => class extends superclass {
static create(...args) {
const [props, ...rest] = args;
const defaults = useDefaults && hasDefaultProps(this)
? this.defaultProps
: {};
const propsWithDefaults = Object.assign({}, defaults, props);
if (useValidation && hasPropTypes(this)) {
PropTypes.checkPropTypes(this.propTypes, propsWithDefaults, 'prop',
`${this.modelName}.create`);
}
return super.create(propsWithDefaults, ...rest);
}
update(...args) {
const modelClass = this.getClass();
if (useValidation && hasPropTypes(modelClass)) {
const props = args[0];
const {
propTypes,
modelName,
} = modelClass;
// Run validators for only the props passed in, not
// all declared PropTypes.
const propTypesToValidate = Object.keys(props).reduce((result, key) => {
if (Object.prototype.hasOwnProperty.call(propTypes, key)) {
return { ...result, [key]: propTypes[key] };
}
return result;
}, {});
PropTypes.checkPropTypes(propTypesToValidate, props, 'prop',
`${modelName}.update`);
}
return super.update(...args);
}
};
}
export default getPropTypesMixin();