Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active July 27, 2017 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvergnaud/e6619201063b6b648d394db7af1a8931 to your computer and use it in GitHub Desktop.
Save gvergnaud/e6619201063b6b648d394db7af1a8931 to your computer and use it in GitHub Desktop.
/**
* 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