]>
Commit | Line | Data |
---|---|---|
1 | import { values } from 'lodash' | |
2 | import * as Sequelize from 'sequelize' | |
3 | import { JobCategory, JobState } from '../../../shared/models/job.model' | |
4 | import { JOB_CATEGORIES, JOB_STATES } from '../../initializers' | |
5 | import { addMethodsToModel, getSort } from '../utils' | |
6 | import { JobAttributes, JobInstance, JobMethods } from './job-interface' | |
7 | ||
8 | let Job: Sequelize.Model<JobInstance, JobAttributes> | |
9 | let listWithLimitByCategory: JobMethods.ListWithLimitByCategory | |
10 | let listForApi: JobMethods.ListForApi | |
11 | let toFormattedJSON: JobMethods.ToFormattedJSON | |
12 | ||
13 | export default function defineJob (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { | |
14 | Job = sequelize.define<JobInstance, JobAttributes>('Job', | |
15 | { | |
16 | state: { | |
17 | type: DataTypes.ENUM(values(JOB_STATES)), | |
18 | allowNull: false | |
19 | }, | |
20 | category: { | |
21 | type: DataTypes.ENUM(values(JOB_CATEGORIES)), | |
22 | allowNull: false | |
23 | }, | |
24 | handlerName: { | |
25 | type: DataTypes.STRING, | |
26 | allowNull: false | |
27 | }, | |
28 | handlerInputData: { | |
29 | type: DataTypes.JSON, | |
30 | allowNull: true | |
31 | } | |
32 | }, | |
33 | { | |
34 | indexes: [ | |
35 | { | |
36 | fields: [ 'state', 'category' ] | |
37 | } | |
38 | ] | |
39 | } | |
40 | ) | |
41 | ||
42 | const classMethods = [ | |
43 | listWithLimitByCategory, | |
44 | listForApi | |
45 | ] | |
46 | const instanceMethods = [ | |
47 | toFormattedJSON | |
48 | ] | |
49 | addMethodsToModel(Job, classMethods, instanceMethods) | |
50 | ||
51 | return Job | |
52 | } | |
53 | ||
54 | toFormattedJSON = function (this: JobInstance) { | |
55 | return { | |
56 | id: this.id, | |
57 | state: this.state, | |
58 | category: this.category, | |
59 | handlerName: this.handlerName, | |
60 | handlerInputData: this.handlerInputData, | |
61 | createdAt: this.createdAt, | |
62 | updatedAt: this.updatedAt | |
63 | } | |
64 | } | |
65 | ||
66 | // --------------------------------------------------------------------------- | |
67 | ||
68 | listWithLimitByCategory = function (limit: number, state: JobState, jobCategory: JobCategory) { | |
69 | const query = { | |
70 | order: [ | |
71 | [ 'id', 'ASC' ] | |
72 | ], | |
73 | limit: limit, | |
74 | where: { | |
75 | state, | |
76 | category: jobCategory | |
77 | } | |
78 | } | |
79 | ||
80 | return Job.findAll(query) | |
81 | } | |
82 | ||
83 | listForApi = function (start: number, count: number, sort: string) { | |
84 | const query = { | |
85 | offset: start, | |
86 | limit: count, | |
87 | order: [ getSort(sort) ] | |
88 | } | |
89 | ||
90 | return Job.findAndCountAll(query).then(({ rows, count }) => { | |
91 | return { | |
92 | data: rows, | |
93 | total: count | |
94 | } | |
95 | }) | |
96 | } |