mysql.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import { createPool, createConnection } from 'mysql2/promise'
  2. import { isWorker } from 'node:cluster'
  3. import { cpus } from 'node:os'
  4. import { clientOpts } from '../config.js'
  5. const client = await createConnection(clientOpts)
  6. const res = await client.query('SHOW VARIABLES LIKE "max_connections"')
  7. let maxConnections = 150
  8. if (isWorker) {
  9. maxConnections = cpus().length > 2 ? Math.ceil(res[0][0].Value * 0.96 / cpus().length) : maxConnections
  10. }
  11. await client.end()
  12. const pool = createPool(Object.assign({ ...clientOpts }, {
  13. connectionLimit: maxConnections,
  14. idleTimeout: 600000
  15. }))
  16. const execute = async (text, values) => (await pool.execute(text, values || undefined))[0]
  17. export const fortunes = async () => execute('SELECT * FROM fortune')
  18. export const find = async (id) => execute('SELECT id, randomNumber FROM world WHERE id = ?', [id]).then(arr => arr[0])
  19. export const getAllWorlds = async () => execute('SELECT * FROM world')
  20. export const update = async (obj) => execute('UPDATE world SET randomNumber = ? WHERE id = ?', [obj.randomNumber, obj.id])
  21. await Promise.all([...Array(maxConnections).keys()].map(fortunes))