UNPKG

2.45 kBJavaScriptView Raw
1/*
2 * The MIT License (MIT)
3 *
4 * Copyright (c) 2015 - present Instructure, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25/**
26 * ---
27 * category: utilities/PropTypes
28 * ---
29 * Given a validator function, extends the validator functionality to also
30 * ensure that the prop has been provided if `.isRequired` is specified.
31 *
32 * ```js
33 * function validator (props, propName, componentName) {
34 * const propValue = props[propName]
35 * if (propValue === 'purple') {
36 * return new Error(`Purple is not accepted in ${componentName}!`)
37 * }
38 * }
39 *
40 * validator.isRequired = makeRequirable(validator)
41 * ```
42 *
43 * @param {function} validator - a validator function
44 * @returns {Error} if designated prop is not provided
45 */
46function makeRequirable(validator) {
47 return function (props, propName, componentName) {
48 var propValue = props[propName];
49
50 if (propValue === null || typeof propValue === 'undefined') {
51 return new Error("The prop `".concat(propName, "` is marked as required in `").concat(componentName, "`, but its value is `").concat(propValue, "`"));
52 } else {
53 for (var _len = arguments.length, rest = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
54 rest[_key - 3] = arguments[_key];
55 }
56
57 return validator.apply(void 0, [props, propName, componentName].concat(rest));
58 }
59 };
60}
61
62export default makeRequirable;
63export { makeRequirable };
\No newline at end of file