-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbuildTopicRegExp.js
48 lines (35 loc) · 1.14 KB
/
buildTopicRegExp.js
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
function buildTopicRegExp(topic) {
let pattern = cleanSharedPrefixes(topic);
pattern = escapeRegExpSymbols(pattern)
// Handle single-level wildcard
pattern = pattern.replace(/\\\+/g, '[^/]+');
// Handle multi-level wildcard
pattern = pattern.replace(/#/g, '.*');
return new RegExp('^' + pattern + '$');
}
function cleanSharedPrefixes(originalTopic) {
let topic = originalTopic;
let leadingSlash = false;
// Handle leading slashes
if (topic.startsWith('/')) {
topic = topic.substring(1);
leadingSlash = true;
}
// Cleanup shared subscription prefixes
if (topic.startsWith('$share/')) {
topic = topic.substring('$share/'.length);
const shareGroupEndIdx = topic.indexOf('/');
topic = topic.substring(shareGroupEndIdx + 1);
} else if (topic.startsWith('$queue/')) {
topic = topic.substring('$queue/'.length);
}
// Return leading slash
if (leadingSlash) {
topic = `/${topic}`;
}
return topic;
}
function escapeRegExpSymbols(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
module.exports = buildTopicRegExp;