All files / src message.js

95.35% Statements 41/43
58.33% Branches 14/24
87.5% Functions 7/8
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 523x 3x 7x   3x         3x       3x   4x     3x 3x 3x             8x 1x 1x 7x 1x 1x       8x     8x 8x 8x 8x       5x   5x      
// @flow
import debug from 'debug'
import get from 'lodash/get'E
 
const dbg = debug('woonerf:message')
 
/**
 * Expose a Set of all the keys used
 */
export const KeysUsed = new Set()
 
/**
 * Set the messages object
 */
export function setMessages (newMessages) {
  messages = newMessages
}
 
let messages = {}
Eif (process.env.MESSAGES) {
  setMessages(JSON.parse(process.env.MESSAGES))
}
 
/**
 * Requires a key, defaultMessage and parameters are optional
 */
export default function getMessage (key: string, defaultMessage?: string | Object, parameters?: Object): string {
  if (defaultMessage == null) {
    defaultMessage = ''
    parameters = {}
  } else if (typeof defaultMessage === 'object') {
    parameters = defaultMessage
    defaultMessage = ''
  }
 
  // Store the used key
  KeysUsed.add(key)
 
  // Get the message with "lodash/get" to allow nested keys ('noun.action' => {noun: {action: 'value'}})
  const msg = get(messages, key, defaultMessage)
  const result = parameters ? replaceMessage(msg, parameters) : msg
  dbg(key, result)
  return result
}
 
function replaceMessage (msg, data) {
  return msg.replace(
    new RegExp('%\\((' + Object.keys(data).join('|') + ')\\)', 'g'),
    (m, key) => data.hasOwnProperty(key) ? data[key] : m
  )
}