@lexamica-modules/job-queue
Version:
The package for the Lexamica Job Queue SDK powered by Redis and BullMQ
81 lines (80 loc) • 2.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Workers = void 0;
const bullmq_1 = require("bullmq");
const errors_1 = require("../util/errors");
const encryption_1 = require("../util/encryption");
/**
* Management class for all Workers
*/
class Workers {
// connection to the redis cloud
_connection;
/**
* Initialize an instance of the Worker Management Class
* @param {Redis} connection the Redis connection to use
*/
constructor(connection) {
this._connection = connection;
}
/**
* Add a worker to a given queue with an executer function
* @param {string} queue_name the name of the queue to add this worker to
* @param {JobExecuter} executer function to execute when processing jobs
* @returns {Worker}
*/
addWorker = (queue_name, executer, options, onCompleted, onFailed, onError) => {
// configuration
const removeOnComplete = process.env.JOB_QUEUE_COMPLETIONS
? Number(process.env.JOB_QUEUE_COMPLETIONS)
: 5000;
const removeOnFailure = process.env.JOB_QUEUE_FAILURES
? Number(process.env.JOB_QUEUE_FAILURES)
: 5000;
// configure the handler with the decryption wrapper around the executer
const handler = async (job) => {
// decrypt job data
const decryptedData = (0, encryption_1.decryptPayload)(job.data);
job.data = decryptedData;
await executer(job);
};
// create the worker
const worker = new bullmq_1.Worker(queue_name, handler, {
connection: this._connection,
removeOnComplete: { count: removeOnComplete },
removeOnFail: { count: removeOnFailure },
...options,
});
// optional handlers
if (onCompleted) {
worker.on("completed", onCompleted);
}
if (onFailed) {
worker.on("failed", onFailed);
}
// safety handler
if (onError) {
worker.on("error", onError);
}
else {
worker.on("error", (err) => {
(0, errors_1.handleErrorWithInfo)({
message: `A worker experienced an unexpected error`,
job: "Unknown",
error: err,
});
});
}
// return the worker
return worker;
};
/**
* Finish the worker's current job and then pause it from processing more jobs.
* @param {Worker} worker the worker instance
* @returns {Promise<void>}
*/
closeWorker = async (worker) => {
return worker.close();
};
}
exports.Workers = Workers;