import { values } from 'lodash'
-import * as Sequelize from 'sequelize'
+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'
-import { JOB_STATES } from '../../initializers'
+@Table({
+ tableName: 'job',
+ indexes: [
+ {
+ fields: [ 'state', 'category' ]
+ }
+ ]
+})
+export class JobModel extends Model<JobModel> {
+ @AllowNull(false)
+ @Column(DataType.ENUM(values(JOB_STATES)))
+ state: JobState
-import { addMethodsToModel } from '../utils'
-import {
- JobClass,
- JobInstance,
- JobAttributes,
+ @AllowNull(false)
+ @Column(DataType.ENUM(values(JOB_CATEGORIES)))
+ category: JobCategory
- JobMethods
-} from './job-interface'
+ @AllowNull(false)
+ @Column
+ handlerName: string
-let Job: Sequelize.Model<JobInstance, JobAttributes>
-let listWithLimit: JobMethods.ListWithLimit
+ @AllowNull(true)
+ @Column(DataType.JSON)
+ handlerInputData: any
-export default function defineJob (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
- Job = sequelize.define<JobInstance, JobAttributes>('Job',
- {
- state: {
- type: DataTypes.ENUM(values(JOB_STATES)),
- allowNull: false
- },
- handlerName: {
- type: DataTypes.STRING,
- allowNull: false
- },
- handlerInputData: {
- type: DataTypes.JSON,
- allowNull: true
+ @CreatedAt
+ creationDate: Date
+
+ @UpdatedAt
+ updatedOn: Date
+
+ static listWithLimitByCategory (limit: number, state: JobState, jobCategory: JobCategory) {
+ const query = {
+ order: [
+ [ 'id', 'ASC' ]
+ ],
+ limit: limit,
+ where: {
+ state,
+ category: jobCategory
}
- },
- {
- indexes: [
- {
- fields: [ 'state' ]
- }
- ]
}
- )
- const classMethods = [ listWithLimit ]
- addMethodsToModel(Job, classMethods)
+ return JobModel.findAll(query)
+ }
- return Job
-}
+ 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
+ }
+ })
+ }
-listWithLimit = function (limit: number, state: string, callback: JobMethods.ListWithLimitCallback) {
- const query = {
- order: [
- [ 'id', 'ASC' ]
- ],
- limit: limit,
- where: {
- state
+ toFormattedJSON () {
+ return {
+ id: this.id,
+ state: this.state,
+ category: this.category,
+ handlerName: this.handlerName,
+ handlerInputData: this.handlerInputData,
+ createdAt: this.createdAt,
+ updatedAt: this.updatedAt
}
}
-
- return Job.findAll(query).asCallback(callback)
}