all files / src/helpers/ templated-text.js

100% Statements 27/27
100% Branches 10/10
100% Functions 1/1
100% Lines 26/26
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 5110×       23× 23×           18× 18×     18× 18× 18× 18× 18×       18× 18×   18×             17× 17× 18× 18×   17×        
import { isPlainObject, isString } from 'lodash'
import XRegExp from 'xregexp'
import {
    MISMATCH_ERROR, INVALID_RAW_TEXT, INVALID_TEMPLATE
} from '../constants/language/helpers/templated-text.js'
 
const templatedText = (rawText, template = {}) => {
    if (!isString(rawText)) {
        const invalidRawText = templatedText(
            INVALID_RAW_TEXT, {
                'TYPE_RECEIVED': Object.prototype.toString.call(rawText)
            }
        )
        throw new Error(invalidRawText)
    }
    const placeHolders = getPlaceHolders(rawText)
    return getFinalText(rawText, placeHolders, template)
}
 
const getPlaceHolders = (rawText) => {
    const placeHolderPattern = /\{\{[A-Z_1-9]+\}\}/g
    const placeHolders = rawText.match(placeHolderPattern) || []
    const bracketPattern = /\{\{|\}\}/g
    return placeHolders.map(
        placeHolder => placeHolder.replace(bracketPattern, '')
    )
}
 
const getFinalText = (rawText, placeHolders, template) => {
    const mismatches = placeHolders.filter(
        placeHolder => !template[placeHolder]
    )
    if (mismatches.length > 0) {
        const templatedMismatchError = templatedText(
            MISMATCH_ERROR, {
                'MISMATCHED_PLACE_HOLDERS': mismatches.join(', '),
                'PLACE_HOLDERS': placeHolders.join(', ')
            }
        )
        throw new Error(templatedMismatchError)
    }
    let finalText = rawText
    Object.keys(template).forEach(placeHolder => {
        const placeHolderRegex = XRegExp(`{{${placeHolder}}}`, 'g')
        finalText = finalText.replace(placeHolderRegex, template[placeHolder])
    })
    return finalText.trim()
}
 
export default templatedText