-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
jobs.ts
54 lines (53 loc) · 1.75 KB
/
jobs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import app from "@adonisjs/core/services/app"
import { fsImportAll } from "@poppinss/utils"
import Job from "./base_job.js"
import { NodeResqueJob } from './types.js'
export async function importAllJobs() {
const jobs: Record<string, unknown> = await fsImportAll(app.makePath('app/jobs'), {
ignoreMissingRoot: true
})
/**
* Duck typing check
* @param job
* @returns
*/
const isValidJob = (job: any): job is typeof Job => {
if (!job) {
return false
}
if (typeof job?.prototype?.perform !=='function') {
return false
}
if (typeof job?.prototype?.enqueue !== 'function') {
return false
}
return true
}
const Jobs = Object.values(jobs).filter(isValidJob)
return Jobs.reduce(async (initlizedAccumulator, Job) => {
let accumulator = await initlizedAccumulator
const job = await app.container.make(Job)
if (!Array.isArray(job.plugins)) {
job.plugins = []
}
const plugins = job.plugins.map(([plugin]) => plugin)
const pluginOptions = job.plugins.reduce((acc, [plugin, options]) => {
acc[plugin.name] = options
return acc
}, {} as Record<string, any>)
accumulator[Job.name] = {
perform: async (...args: any[]) => {
try {
const jobResult = await job.perform.call(job, ...args)
return jobResult
} catch (error) {
return job.handleError.call(job, error)
}
},
job,
plugins,
pluginOptions
}
return accumulator
}, Promise.resolve<Record<string, NodeResqueJob>>({}))
}