jobs.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import * as express from 'express'
  2. import { ResultList } from '../../../shared'
  3. import { Job, JobType, JobState } from '../../../shared/models'
  4. import { UserRight } from '../../../shared/models/users'
  5. import { JobQueue } from '../../lib/job-queue'
  6. import {
  7. asyncMiddleware,
  8. authenticate,
  9. ensureUserHasRight,
  10. jobsSortValidator,
  11. setDefaultPagination,
  12. setDefaultSort
  13. } from '../../middlewares'
  14. import { paginationValidator } from '../../middlewares/validators'
  15. import { listJobsValidator } from '../../middlewares/validators/jobs'
  16. import { isArray } from '../../helpers/custom-validators/misc'
  17. const jobsRouter = express.Router()
  18. jobsRouter.get('/:state',
  19. authenticate,
  20. ensureUserHasRight(UserRight.MANAGE_JOBS),
  21. paginationValidator,
  22. jobsSortValidator,
  23. setDefaultSort,
  24. setDefaultPagination,
  25. asyncMiddleware(listJobsValidator),
  26. asyncMiddleware(listJobs)
  27. )
  28. // ---------------------------------------------------------------------------
  29. export {
  30. jobsRouter
  31. }
  32. // ---------------------------------------------------------------------------
  33. async function listJobs (req: express.Request, res: express.Response, next: express.NextFunction) {
  34. const state: JobState = req.params.state
  35. const asc = req.query.sort === 'createdAt'
  36. const jobs = await JobQueue.Instance.listForApi(state, req.query.start, req.query.count, asc)
  37. const total = await JobQueue.Instance.count(state)
  38. const result: ResultList<any> = {
  39. total,
  40. data: jobs.map(j => formatJob(j, state))
  41. }
  42. return res.json(result)
  43. }
  44. function formatJob (job: any, state: JobState): Job {
  45. const error = isArray(job.stacktrace) && job.stacktrace.length !== 0 ? job.stacktrace[0] : null
  46. return {
  47. id: job.id,
  48. state: state,
  49. type: job.queue.name as JobType,
  50. data: job.data,
  51. error,
  52. createdAt: new Date(job.timestamp),
  53. finishedOn: new Date(job.finishedOn),
  54. processedOn: new Date(job.processedOn)
  55. }
  56. }