message-extractor.js 1.53 KB
/* eslint-disable no-console */
const MODULE_NAME = 'MESSAGE-PARSER.FINDER';

/**
 * Mencari nilai berdasarkan array of pattern
 * @date 2021-07-05
 * @param {Array} rules
 * @param {string} originalMessage
 * @param {any} isDebug
 * @returns {string} string yang sesuai pattern, null jika tidak ditemukan
 */
module.exports = (rules, originalMessage, isDebug) => {
    if (!Array.isArray(rules)) return null;
    if (typeof originalMessage !== 'string') return null;

    const msg = originalMessage.trim();

    if (!rules || !msg) return null;

    const ruleCount = rules.length;
    for (let i = 0; i < ruleCount; i += 1) {
        const rule = rules[i];

        // eslint-disable-next-line no-continue
        if (!rule || !rule.pattern || rule.disable || rule.disabled) continue;

        const patternConstructorName = rule.pattern.constructor.name;
        const re = patternConstructorName === 'RegExp' ? rule.pattern
            : new RegExp(rule.pattern, rule.flags || '');

        const matches = msg.match(re);
        let result = matches && matches[rule.idx];

        if (result && rule.postprocessing && typeof rule.postprocessing === 'function') {
            result = rule.postprocessing(result);
        }

        if (result) {
            if (isDebug) {
                console.log(`${MODULE_NAME} 9FAF9286: Found matches`, { isDebug, result, rule });
            }

            return result;
        }
    }

    if (isDebug) {
        console.log(`${MODULE_NAME} 0240860D: Matches not found`, { isDebug });
    }

    return null;
};