Improve check jobs parameters tests
[oweals/peertube.git] / server / models / job / job.ts
1 import { values } from 'lodash'
2 import { AllowNull, Column, CreatedAt, DataType, Model, Table, UpdatedAt } from 'sequelize-typescript'
3 import { JobCategory, JobState } from '../../../shared/models'
4 import { JOB_CATEGORIES, JOB_STATES } from '../../initializers'
5 import { getSort } from '../utils'
6
7 @Table({
8   tableName: 'job',
9   indexes: [
10     {
11       fields: [ 'state', 'category' ]
12     }
13   ]
14 })
15 export class JobModel extends Model<JobModel> {
16   @AllowNull(false)
17   @Column(DataType.ENUM(values(JOB_STATES)))
18   state: JobState
19
20   @AllowNull(false)
21   @Column(DataType.ENUM(values(JOB_CATEGORIES)))
22   category: JobCategory
23
24   @AllowNull(false)
25   @Column
26   handlerName: string
27
28   @AllowNull(true)
29   @Column(DataType.JSON)
30   handlerInputData: any
31
32   @CreatedAt
33   createdAt: Date
34
35   @UpdatedAt
36   updatedAt: Date
37
38   static listWithLimitByCategory (limit: number, state: JobState, jobCategory: JobCategory) {
39     const query = {
40       order: [
41         [ 'id', 'ASC' ]
42       ],
43       limit: limit,
44       where: {
45         state,
46         category: jobCategory
47       }
48     }
49
50     return JobModel.findAll(query)
51   }
52
53   static listForApi (start: number, count: number, sort: string) {
54     const query = {
55       offset: start,
56       limit: count,
57       order: [ getSort(sort) ]
58     }
59
60     return JobModel.findAndCountAll(query).then(({ rows, count }) => {
61       return {
62         data: rows,
63         total: count
64       }
65     })
66   }
67
68   toFormattedJSON () {
69     return {
70       id: this.id,
71       state: this.state,
72       category: this.category,
73       handlerName: this.handlerName,
74       handlerInputData: this.handlerInputData,
75       createdAt: this.createdAt,
76       updatedAt: this.updatedAt
77     }
78   }
79 }