bdn-pocket
Version:
pocket tools for managing redux and redux-saga
77 lines (63 loc) • 1.98 kB
JavaScript
import reduce from 'ramda/src/reduce'
import mapObjIndexed from 'ramda/src/mapObjIndexed'
import stampit from '@stamp/it'
import is from '@stamp/is'
import Types, { mixed } from './types'
export { Types }
function argsToPropTypes(propTypes) {
const reducer = (acc, name) => {
if (!is.isString(name)) {
throw new ReferenceError(`expected args prop types to be only string - ${typeof name} received`)
}
acc[name] = mixed({ name })
return acc
}
return reduce(reducer, {}, propTypes)
}
function checkObjPropTypes(propTypes = {}) {
const mapper = (v, key) => {
if (is.isFunction(v) || is.isFunction(v.isValid)) {
return is.isStamp(v) ? v() : v
}
throw new ReferenceError(`expected ${key} prop type to be a function - ${typeof v} received`)
}
return mapObjIndexed(mapper, propTypes)
}
const PropTypes = stampit
.deepConf({
propTypeModel: {},
})
.statics({
propTypes(...args) {
if (args.length === 0) return
const firstArg = args[0]
const argsToProps = is.isObject(firstArg) ?
checkObjPropTypes(firstArg) :
argsToPropTypes(args)
// deep merge all the pairs to the modelProps object
return this.deepConf({
propTypeModel: argsToProps
})
},
hasPropTypes() {
const { propTypeModel } = this.compose.deepConfiguration
return Object.keys(propTypeModel).length > 0
}
})
.init((props = {}, { stamp }) => {
const { propTypeModel } = stamp.compose.deepConfiguration
Object.keys(propTypeModel).forEach(key => {
const propType = propTypeModel[key]
propType.isValid(props, key)
})
})
// const a = PropTypes.propTypes('a')({a: 'a'})
// const b = PropTypes.propTypes('b')({b: 'b'})
// import { number } from './types'
// // const c = PropTypes.propTypes({ a: number({ required: true }) })
// const c = PropTypes.propTypes({
// a: number,
// b: string,
// })
// c({a: 'a', b: 'b'})
export default PropTypes