Rip out client sharding logic into its own class

This commit is contained in:
Schuyler Cebulskie
2016-09-26 23:23:56 -04:00
parent d240fe4182
commit 4fe30aa4d3
3 changed files with 56 additions and 19 deletions

47
src/sharding/ShardUtil.js Normal file
View File

@@ -0,0 +1,47 @@
/**
* Helper class for sharded clients
*/
class ShardUtil {
/**
* @param {Client} client Client of the current shard
*/
constructor(client) {
this.client = client;
}
/**
* Handles an IPC message
* @param {*} message Message received
*/
_handleMessage(message) {
if (!message) return;
if (message._eval) {
try {
process.send({ _evalResult: eval(message._eval) });
} catch (err) {
process.send({ _evalError: err });
}
} else if (message._fetchProp) {
const props = message._fetchProp.split('.');
let value = this; // eslint-disable-line consistent-this
for (const prop of props) value = value[prop];
process.send({ _fetchProp: message._fetchProp, _fetchPropValue: value });
}
}
/**
* Creates/gets the singleton of this class
* @param {Client} client Client to use
* @returns {ShardUtil}
*/
static singleton(client) {
if (!this._singleton) {
this._singleton = new this(client);
} else {
client.emit('error', 'Multiple clients created in child process; only the first will handle sharding helpers.');
}
return this._singleton;
}
}
module.exports = ShardUtil;