adonisjs-jobs
Version:
Job processing for AdonisJS
37 lines (36 loc) • 1.33 kB
JavaScript
import ClosureJob from './jobs/closure_job.js';
import * as devalue from 'devalue';
import { REDUCERS } from './devalue.js';
export class Dispatcher {
app;
constructor(app) {
this.app = app;
}
async dispatch(jobOrClosure, payload, options = {}) {
// @ts-ignore
const config = this.app.config.get('jobs', {});
let isClosure = !(typeof jobOrClosure === 'function' && /^class\s/.test(jobOrClosure.toString()));
if (isClosure && config.enableSerializedJob !== true) {
throw new Error('Closure jobs are not enabled');
}
let job = isClosure ? ClosureJob : jobOrClosure;
payload = isClosure
? {
serializedClosure: jobOrClosure.toString(),
}
: payload;
// @ts-ignore
const queues = await this.app.container.make('jobs.queues');
const queueName = options.queueName || config.queues[0];
const queue = queues[queueName];
if (!queue) {
throw new Error(`Queue ${queueName} not found`);
}
const reducers = {
...REDUCERS,
...(config.serialization?.reducers || {}),
};
const bullmqJob = await queue.add(job.name, devalue.stringify(payload, reducers), options);
return bullmqJob.id;
}
}