message-extractor.js
1.53 KB
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
52
/* 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;
};