All files post.js

100% Statements 21/21
100% Branches 13/13
100% Functions 5/5
100% Lines 16/16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27      2x 2x 2x     5x 41x 41x 41x 14x 56x 12x     14x 12x 6x     27x 27x 27x    
import { argumentError, isValid } from './utils'
import { run } from './run'
 
const warnWork = msg => {
  console.warn(`WARN! ${msg} is not a registered action for this worker`)
  return `${msg} is not a registered action for this worker`
}
 
export const post = actions => (msg = null, args) => {
  const validMessage = isValid(msg)('string')
  const validArgs = isValid(args)(['array', 'undefined'])
  if (validMessage && validArgs) {
    const work = actions
      .filter(({ message }) => JSON.stringify(message) === JSON.stringify(msg))
      .map(action => action.func)
      .pop()
 
    if (!work) return run(warnWork, [JSON.stringify(msg)])
    if (args) return run(work, args)
    return run(work)
  }
 
  if (!validMessage) console.error(argumentError({ expected: 'a string', received: msg }))
  if (!validArgs) console.error(argumentError({ expected: 'an array', received: args }))
  return null
}