Last active
July 27, 2017 09:26
-
-
Save gvergnaud/e6619201063b6b648d394db7af1a8931 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Backbone.Model shape propType checker for the `prop-types` package. | |
*/ | |
import PropTypesSecret from 'prop-types/lib/ReactPropTypesSecret'; | |
function createChainableTypeChecker(validate) { | |
function checkType(isRequired, props, propName, componentName, location, propFullName) { | |
var value = props[propName]; | |
propFullName = propFullName || propName; | |
if (value === null || value === undefined) { | |
return isRequired | |
? new Error( | |
'Required ' + | |
location + | |
' `' + | |
propFullName + | |
'` was not specified in ' + | |
'`' + | |
componentName + | |
'`.' | |
) | |
: null; | |
} | |
return validate( | |
props, | |
propFullName, | |
componentName, | |
location, | |
propFullName, | |
PropTypesSecret | |
); | |
} | |
var PropType = checkType.bind(null, false); | |
PropType.isRequired = checkType.bind(null, true); | |
return PropType; | |
} | |
function getType(x) { | |
return Array.isArray(x) ? 'array' : typeof x; | |
} | |
export function modelShape(shapeTypes) { | |
return createChainableTypeChecker(function(props, propName, componentName, location) { | |
var value = props[propName]; | |
var propType = getType(value); | |
if (propType !== 'object' || !value.attributes) { | |
return new Error( | |
'Invalid ' + | |
location + | |
' `' + | |
propName + | |
'` of type `' + | |
propType + | |
'` ' + | |
'supplied to `' + | |
componentName + | |
'`, expected `Backbone.Model`.' | |
); | |
} | |
for (var key in shapeTypes) { | |
var checker = shapeTypes[key]; | |
if (!checker) continue; | |
var error = checker( | |
value.attributes, | |
key, | |
componentName, | |
location, | |
propName + ".get('" + key + "')", | |
PropTypesSecret | |
); | |
if (error) return error; | |
} | |
return null; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment