Skip to content

feat: add RegExp support to PoolCluster #3451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 18 additions & 14 deletions lib/pool_cluster.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ const getMonotonicMilliseconds = function () {
return Math.floor(ms);
};

const patternRegExp = function (pattern) {
if (pattern instanceof RegExp) {
return pattern;
}

const source = pattern
.replace(/([.+?^=!:${}()|[\]/\\])/g, '\\$1')
.replace(/\*/g, '.*');

return new RegExp(`^${source}$`);
};

class PoolNamespace {
constructor(cluster, pattern, selector) {
this._cluster = cluster;
Expand Down Expand Up @@ -256,20 +268,12 @@ class PoolCluster extends EventEmitter {
let currentTime = 0;
let foundNodeIds = this._findCaches[pattern];

if (typeof this._findCaches[pattern] === 'undefined') {
if (pattern === '*') {
// all
foundNodeIds = this._serviceableNodeIds;
} else if (this._serviceableNodeIds.indexOf(pattern) !== -1) {
// one
foundNodeIds = [pattern];
} else {
// wild matching
const keyword = pattern.substring(pattern.length - 1, 0);
foundNodeIds = this._serviceableNodeIds.filter((id) =>
id.startsWith(keyword)
);
}
if (foundNodeIds === undefined) {
const expression = patternRegExp(pattern);

foundNodeIds = this._serviceableNodeIds.filter((id) =>
id.match(expression)
);
}

this._findCaches[pattern] = foundNodeIds;
Expand Down
36 changes: 36 additions & 0 deletions test/esm/integration/pool-cluster/test-promise-wrapper.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,40 @@ const { createPoolCluster } = require('../../../../promise.js');

poolCluster.end();
});

await test(async () => {
const poolCluster = createPoolCluster();
poolCluster.add('SLAVE', common.config);

try {
await poolCluster.getConnection('SLAVE1');
assert.fail('An error was expected');
} catch (error) {
assert.equal(
error.code,
'POOL_NOEXIST',
'should throw when PoolNamespace does not exist'
);
} finally {
poolCluster.end();
}
});

await test(async () => {
const poolCluster = createPoolCluster();
poolCluster.add('SLAVE1', common.config);

try {
const connection = await poolCluster.getConnection(/SLAVE[12]/);
assert.equal(
connection.connection._clusterId,
'SLAVE1',
'should match regex pattern'
);
} catch (error) {
assert.fail('should not throw');
} finally {
poolCluster.end();
}
});
})();
Loading