UNPKG

autosql

Version:

An auto-parser of JSON into SQL.

58 lines (57 loc) 2.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const workerPool_1 = __importDefault(require("./workerPool")); const defaults_1 = require("../config/defaults"); class WorkerHelper { static workerPool = null; static async run(dbConfig, method, paramsArray, workerSize = defaults_1.defaults.maxWorkers) { // ✅ Initialize worker pool only once if (!this.workerPool) { this.workerPool = new workerPool_1.default(workerSize, dbConfig); } const workerPromises = []; let activeWorkers = 0; let taskIndex = 0; return new Promise((resolve) => { const results = []; const processNextTask = () => { if (taskIndex >= paramsArray.length) { // ✅ Check if there are no active workers & no remaining tasks if (activeWorkers === 0) { console.log(`\n✅ All Workers Completed, completed: ${taskIndex - 1} tasks ✅`); resolve(results); this.closePool(); } return; } if (activeWorkers < workerSize) { // ✅ Assign a task to an available worker const currentTaskIndex = taskIndex++; const params = paramsArray[currentTaskIndex]; activeWorkers++; const workerPromise = this.workerPool.runTask(method, params).then((result) => { results[currentTaskIndex] = result; activeWorkers--; processNextTask(); // Assign next task when a worker becomes available return result; }); workerPromises.push(workerPromise); } }; // ✅ Start the initial batch of tasks for (let i = 0; i < workerSize && i < paramsArray.length; i++) { processNextTask(); } }); } static closePool() { if (this.workerPool) { this.workerPool.close(); this.workerPool = null; } } } exports.default = WorkerHelper;