let connection = null;
function getDBConnection(callback) {
if (connection !== null) {
return callback(null, connection);
}
mongo.connect(..., (error, connect) => {
if (error) {
return callback(error);
}
connection = connect;
callback(null, connection);
});
}
server = http.createServer((req, res) => {
getDBConnection((error, connection) => {
if (error) {
res.statusCode = 500;
res.end();
return;
}
// ... working
})
});
const socket = io(config.api.socketHost, {
autoConnect: true,
reconnection: true,
timeout: 35000,
reconnectionDelay: 600,
reconnectionDelayMax: 3500,
query: {
auth: config.api.socketKey
}
})
.open();
const hashes = new Set();
try {
socket
.on('connect', () => {
logger.info('Connect to socket API')
})
.on('disconnect', () => {
logger.error('Disconnect to socket API')
})
.on('connect_error', (error) => {
logger.error('Error connect to socket API', error)
})
.on('connect_timeout', (error) => {
logger.error('Сonnect to socket API timeout', error)
})
.on('reconnecting', (attempt) => {
logger.warn('Error reconnecting to socket API', null, {
attempt: attempt
})
})
.on('reconnect_failed', (reconnectionAttempts) => {
logger.warn('Failed connect to socket API', null, {
reconnectionAttempts: reconnectionAttempts
})
})
.on('reconnect_error', (error) => {
logger.error('Error reconect to socket API', error)
})
.on('list', (data) => {
// Тут уже реализовывать другую логику с хэшами. Например так
if (!hashes.has(data.hash)) {
return; // Если нет хэша
}
hashes.delete(data.hash);
doSomething(data);
});
} catch (error) {
logger.error('Error conect socket API', error)
}
function emitListHash() {
const hash = crypto.randomBytes(30).toString('hex');
hashes.add(hash);
socket.emit('list', {
auth: key,
hash
});
}