adonis5-queue
Version:
Adonis JS 5 queue package based backed by Kue and Kue-scheduler
91 lines (90 loc) • 3.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const index_1 = require("../errors/index");
const utils_1 = require("./../utils");
const path_1 = require("path");
/**
* Register and preload consumer processes
*
* @version 2.0.0
* @adonis-version 4.0+
*/
class JobRegister {
constructor(Config, appRootPath) {
this.config = Config;
this.appRootPath = appRootPath;
}
/**
* Inject Kue Queue into the app
* @param {Kue/Queue} queue
*/
setQueue(queue) {
this.queue = queue;
return this;
}
/**
* Load all job classes aynchronously
* @return {Promise}
*/
async listenForAppJobs() {
try {
const filePaths = await this.jobFilePaths();
await this.requireAndProcessJobs(filePaths);
return {
message: 'Preprocessed jobs and started queue listener!',
};
}
catch (error) {
console.log(error);
const e = new index_1.JobDirectoryNotFoundError('Consumer/Producer directory not found. Please make sure to create job with node ace queue:job');
e.setError(error);
throw e;
}
}
/**
* Get all job file paths
* @return {Promise<String>} File paths
*/
jobFilePaths() {
return (0, utils_1.listFiles)((0, path_1.join)(this.appRootPath, this.config.consumerPath));
}
/**
* Require all available jobs and process them
* @param {Array} filePaths Job class files
* @return {Void}
*/
async requireAndProcessJobs(filePaths) {
filePaths.forEach((path) => {
// path = path.replace('.ts', '.js')
const fullPath = `${(0, path_1.join)(this.appRootPath, this.config.consumerPath)}/${path}`;
if (path.includes('index') || path.includes('.map')) {
return;
}
const Job = require(fullPath).default;
const concurrency = Job.concurrency || 1;
this.queue.process(Job.type, concurrency, (job, ctx, done) => {
// recreate the job and apply the handle function
const appJob = new Job(job.data);
appJob.setContext(ctx);
try {
const res = appJob.handle.apply(appJob);
if (res instanceof Promise) {
res.then((success) => done(null, success), (error) => {
const e = new index_1.JobProcessError(`Failed to process job ${Job.name}!`);
done(e.setError(error).updateMessage());
});
}
else {
// just a regular call
done(null, res);
}
}
catch (error) {
const e = new index_1.JobProcessError(`Failed to process job ${Job.name}!`);
done(e.setError(error).updateMessage());
}
});
});
}
}
exports.default = JobRegister;