/**
* Module dependencies
*/
const flatten = require('./flatten')
const compose = require('./compose')
const isFSA = require('./is-fsa')
const slice = require('sliced')
const Tree = require('./tree')
const fold = require('./fold')
const ident = (v) => v
/**
* Export `Alley`
*/
module.exports = Alley
/**
* Initialize `Alley`
*/
function Alley () {
const tree = Tree()
return {
send: Send(tree),
use: Use(tree),
alley: true,
tree: tree
}
}
/**
* Send a value
*/
function Send (tree) {
return function send (payload) {
const action = fold(slice(arguments))
if (!isFSA(action)) throw nonstandard(action)
const root = tree.up('root') || []
const parents = tree.up(action.type) || []
const fn = compose(flatten(root.concat(parents)))
return fn(action, ident).then(() => action)
}
}
/**
* Use a function
*/
function Use (tree) {
return function use (namespace, fn) {
if (arguments.length === 1) {
fn = namespace
namespace = 'root'
}
let fns = tree(namespace) || []
fns = fns.concat(fn)
tree(namespace, fns)
}
}
/**
* Non-standard
*
* @param {Mixed} action
* @return {Error}
*/
function nonstandard (action) {
return new Error('resolved action (' + JSON.stringify(action) + ') is not the correct format. Please refer to the spec: https://github.com/acdlite/flux-standard-action#actions')
}
|