Basic api documentation #7 (#220)
[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       logging: false
49     }
50
51     return JobModel.findAll(query)
52   }
53
54   static listForApi (start: number, count: number, sort: string) {
55     const query = {
56       offset: start,
57       limit: count,
58       order: [ getSort(sort) ]
59     }
60
61     return JobModel.findAndCountAll(query).then(({ rows, count }) => {
62       return {
63         data: rows,
64         total: count
65       }
66     })
67   }
68
69   toFormattedJSON () {
70     return {
71       id: this.id,
72       state: this.state,
73       category: this.category,
74       handlerName: this.handlerName,
75       handlerInputData: this.handlerInputData,
76       createdAt: this.createdAt,
77       updatedAt: this.updatedAt
78     }
79   }
80 }