Dúvida: JS Functions Pattern ?
Filipe, vejo em varias partes do projeto que vc cria uma funcao e utiliza funcoes helpers, mas as declara no corpo da main function. Primeio pensei que fazia isso para usar clousure ou algo assim, mas em muitos casos vejo essas funcoes nao usam clousures.
Isso eh um pattern ? Algum motivo para isso?
async function checkForTooManyConnections(client) { // Main Function
const currentTime = new Date().getTime();
const openedConnectionsMaxAge = 10000;
const maxConnectionsTolerance = 0.9;
if (cache.maxConnections === null || cache.reservedConnections === null) {
const [maxConnections, reservedConnections] = await getConnectionLimits();
cache.maxConnections = maxConnections;
cache.reservedConnections = reservedConnections;
}
if (
!cache.openedConnections === null ||
!cache.openedConnectionsLastUpdate === null ||
currentTime - cache.openedConnectionsLastUpdate > openedConnectionsMaxAge
) {
const openedConnections = await getOpenedConnections();
cache.openedConnections = openedConnections;
cache.openedConnectionsLastUpdate = currentTime;
}
if (cache.openedConnections > (cache.maxConnections - cache.reservedConnections) * maxConnectionsTolerance) {
return true;
}
return false;
async function getConnectionLimits() { // helper Function
const [maxConnectionsResult, reservedConnectionResult] = await client.query(
'SHOW max_connections; SHOW superuser_reserved_connections;'
);
return [
maxConnectionsResult.rows[0].max_connections,
reservedConnectionResult.rows[0].superuser_reserved_connections,
];
}
async function getOpenedConnections() { helper Function
const openConnectionsResult = await client.query({
text: 'SELECT numbackends as opened_connections FROM pg_stat_database where datname = $1',
values: [process.env.POSTGRES_DB],
});
return openConnectionsResult.rows[0].opened_connections;
}
}