Repository URL to install this package:
|
Version:
3.1.5 ▾
|
class Job {
constructor(type, id, params, reporter) {
this.type = type;
this.id = id;
this.params = params;
this.reporter = reporter;
this.state = {};
this.progress = {
numerator: 0,
denominator: 1,
}
// this.progressTimeout = null;
// this.lastReportingTime = null;
this.logSeq = 1;
}
// Returns a promise
jobPromise() {
return new Promise((resolve, reject) => {
reject(new Error('You must implement the jobPromise method which returns a promise to execute for this job!'));
})
}
assertJobType(type) {
if (type !== this.type) {
throw new Error('Invalid assertion');
}
}
getInitialState() {
return {};
}
validateParams() {
// Implement to validate the params here
}
setState(changes) {
Object.assign(this.state, changes);
this.reporter.state(this.state);
}
executeJob() {
return Promise.resolve().then(() => {
let initial = this.getInitialState();
if (Object.keys(initial).length > 0) {
this.setState(initial);
}
this.validateParams();
return this.jobPromise();
});
}
log(logData) {
this.reporter.addLog(logData, this.logSeq++);
}
queueChildJob(queueId, jobType, jobParams) {
return this.reporter.queueChildJob(queueId, jobType, jobParams);
}
getChildJob(jobId) {
return this.reporter.getChildJob(jobId);
}
waitForJob(jobId) {
return new Promise((resolve, reject) => {
this.log('Waiting for job to complete: ' + jobId);
let i = setInterval(() => {
this.log('Waiting for job to complete: ' + jobId);
let job = this.getChildJob(jobId);
if (job === null) {
clearInterval(i);
reject(new Error('Cannot find job: ' + jobId));
} else {
if (job.status === 3 || job.status === 4) {
clearInterval(i);
resolve(job);
}
}
}, 5000);
})
}
// NOTE: It is up to the job to make sure this method isn't hammered.
setProgressLevel(progressNumerator, progressDenominator) {
this.progress = {
numerator: progressNumerator,
denominator: progressDenominator,
}
this.reporter.progress(this.progress);
}
}
module.exports = Job;