aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/application/application.ts
blob: 8ba40a8951afec013bc579fc3175d8b4af347c5b (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
import * as Sequelize from 'sequelize'

import { addMethodsToModel } from '../utils'
import {
  ApplicationAttributes,
  ApplicationInstance,

  ApplicationMethods
} from './application-interface'

let Application: Sequelize.Model<ApplicationInstance, ApplicationAttributes>
let loadMigrationVersion: ApplicationMethods.LoadMigrationVersion
let updateMigrationVersion: ApplicationMethods.UpdateMigrationVersion
let countTotal: ApplicationMethods.CountTotal

export default function defineApplication (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
  Application = sequelize.define<ApplicationInstance, ApplicationAttributes>('Application',
    {
      migrationVersion: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
        allowNull: false,
        validate: {
          isInt: true
        }
      }
    }
  )

  const classMethods = [
    countTotal,
    loadMigrationVersion,
    updateMigrationVersion
  ]
  addMethodsToModel(Application, classMethods)

  return Application
}

// ---------------------------------------------------------------------------

countTotal = function () {
  return this.count()
}

loadMigrationVersion = function () {
  const query = {
    attributes: [ 'migrationVersion' ]
  }

  return Application.findOne(query).then(data => data ? data.migrationVersion : null)
}

updateMigrationVersion = function (newVersion: number, transaction: Sequelize.Transaction) {
  const options: Sequelize.UpdateOptions = {
    where: {},
    transaction: transaction
  }

  return Application.update({ migrationVersion: newVersion }, options)
}