bdn-pocket
Version:
pocket tools for managing redux and redux-saga
72 lines (57 loc) • 1.71 kB
JavaScript
import isNil from 'ramda/src/isNil'
import propEq from 'ramda/src/propEq'
import find from 'ramda/src/find'
import is from '@stamp/is'
import DefState from './def_state'
const UNALLOWED_KEYS = ['reducers', 'defaultState', 'merge']
const Messenger = DefState
.deepConf({
Messages: []
})
.statics({
merge(Messenger) {
const { Messages } = Messenger.compose.deepConfiguration
let M = this
Messages.forEach(({ key, action, reducer }) => {
M = M.add({
key,
action,
reducer,
})
})
return M
},
add({ key, action, reducer }) {
const { Messages } = this.compose.deepConfiguration
if (isNil(key) ) {
throw new Error(`key must be defined`)
}
if (is.isString(key) === false) {
throw new Error(`key must be a string`)
}
if (UNALLOWED_KEYS.indexOf(key) >= 0) {
throw new Error(`${UNALLOWED_KEYS.join(', ')} are reserved keys`)
}
if (find(propEq('key', key), Messages)) {
throw new Error(`${key} already present in messenger`)
}
if (!action.CONST) {
throw new Error('action must have CONST prop')
}
if (is.isFunction(reducer) === false) {
throw new Error('reducer must be a function')
}
return this.deepConf({
Messages: [{ key, reducer, action }]
})
},
})
.init((o, { stamp, instance }) => {
const { Messages } = stamp.compose.deepConfiguration
instance.reducers = {}
Messages.forEach(({ key, action, reducer }) => {
instance[key] = action
instance.reducers[action.CONST] = reducer.bind(instance)
})
})
export default Messenger