I want to create a pool in my shard manager (server.js) and pass it to shard processes (bot.js). Here is my sharding manager (server.js):
var clientMysqlEvent = require('./database/botpool.js').connection;
const flatted = require('flatted');
const clientMysqlEventserialized = flatted.stringify(clientMysqlEvent);
const { ShardingManager } = require('discord.js');
const shard = new ShardingManager('./bot.js', {
token: config.token,
respawn: true,
});
shard.spawn({ amount: splen, delay: 100, timeout: 120000 });
//console.log(`[DEBUG/SHARD] Shard ${shard.id} connected to Discord's Gateway.`)
// Sending the data to the shard.
shard.on("ready", () => {
console.log(`[SHARD] Shard ${formatedShardId} connected to Discord's Gateway.`)
// Sending the data to the shard.
shard.send({type: "shardId", data: {shardId: shard.id, shardTotal: splen}});
shard.send({type: "myDb", data: {dbManager: clientMysqlEventserialized}});
});
botpool.js:
const mysql = require('mysql');
var connection = mysql.createPool({
connectionLimit : 20,
host : 'localhost',
user : 'user',
password : 'pass',
database : 'db'
});
connection.on('release', function (connection1) {
console.log('BOT: Connection %d released', connection1.threadId);
});
connection.on('acquire', function (connection1) {
console.log('BOT: Connection %d acquired', connection1.threadId);
});
connection.on('connection', function (connection1) {
console.log('BOT: Connection %d connected', connection1.threadId);
});
connection.on('enqueue', function () {
console.log('BOT: Waiting for available connection slot');
});
exports.connection = connection;
Shard process (bot.js):
const flatted = require('flatted');
var mysql = null;
process.on('message', message => {
if (!message.type) return false;
if (message.type == "shardId") {
console.log(`The shard id is: ${message.data.shardId + Number(1)}`);
console.log(`Total shard number is: ${message.data.shardTotal}`)
clientShardId = message.data.shardId + Number(1)
totalShardIds = message.data.shardTotal
console.log("Captured data: "+clientShardId+"/"+totalShardIds)
client.user.setPresence({ activities: [{ name: `${config.activities} [${message.data.shardId + Number(1)} / ${message.data.shardTotal}]` }] });
} else if (message.type == "myDb") {
//mysql = message.data.dbManager;
mysql = flatted.parse(message.data.dbManager);
//console.log("mysql:")
//console.log(mysql)
};
})
Sadly this approach doesn't do what I want and shard process (bot.js) creates its own pool.
Let me try to solve your problem but I can't confirm if it is correct. The reason your approach is not working is that you are creating the pool connection in the shard manager and then trying to send the connection object to the shard process. However, the connection object cannot be serialized and sent over the IPC channel.
According to the above point of view, you can try: