aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/job/job.ts
blob: 637d4f16c26930842c7e46dca8e435cb524b39a2 (plain) (blame)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { values } from 'lodash'
import { AllowNull, Column, CreatedAt, DataType, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { JobCategory, JobState } from '../../../shared/models'
import { JOB_CATEGORIES, JOB_STATES } from '../../initializers'
import { getSort } from '../utils'

@Table({
  tableName: 'job',
  indexes: [
    {
      fields: [ 'state', 'category' ]
    }
  ]
})
export class JobModel extends Model<JobModel> {
  @AllowNull(false)
  @Column(DataType.ENUM(values(JOB_STATES)))
  state: JobState

  @AllowNull(false)
  @Column(DataType.ENUM(values(JOB_CATEGORIES)))
  category: JobCategory

  @AllowNull(false)
  @Column
  handlerName: string

  @AllowNull(true)
  @Column(DataType.JSON)
  handlerInputData: any

  @CreatedAt
  createdAt: Date

  @UpdatedAt
  updatedAt: Date

  static listWithLimitByCategory (limit: number, state: JobState, jobCategory: JobCategory) {
    const query = {
      order: [
        [ 'id', 'ASC' ]
      ],
      limit: limit,
      where: {
        state,
        category: jobCategory
      }
    }

    return JobModel.findAll(query)
  }

  static listForApi (start: number, count: number, sort: string) {
    const query = {
      offset: start,
      limit: count,
      order: [ getSort(sort) ]
    }

    return JobModel.findAndCountAll(query).then(({ rows, count }) => {
      return {
        data: rows,
        total: count
      }
    })
  }

  toFormattedJSON () {
    return {
      id: this.id,
      state: this.state,
      category: this.category,
      handlerName: this.handlerName,
      handlerInputData: this.handlerInputData,
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    }
  }
}