aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/video/author.ts
blob: c30cc306df0f7d3db8aae722f1e1b375adf21c05 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import * as Sequelize from 'sequelize'

import { isUserUsernameValid } from '../../helpers'

import { addMethodsToModel } from '../utils'
import {
  AuthorInstance,
  AuthorAttributes,

  AuthorMethods
} from './author-interface'

let Author: Sequelize.Model<AuthorInstance, AuthorAttributes>
let findOrCreateAuthor: AuthorMethods.FindOrCreateAuthor

export default function defineAuthor (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
  Author = sequelize.define<AuthorInstance, AuthorAttributes>('Author',
    {
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          usernameValid: value => {
            const res = isUserUsernameValid(value)
            if (res === false) throw new Error('Username is not valid.')
          }
        }
      }
    },
    {
      indexes: [
        {
          fields: [ 'name' ]
        },
        {
          fields: [ 'podId' ]
        },
        {
          fields: [ 'userId' ],
          unique: true
        },
        {
          fields: [ 'name', 'podId' ],
          unique: true
        }
      ]
    }
  )

  const classMethods = [ associate, findOrCreateAuthor ]
  addMethodsToModel(Author, classMethods)

  return Author
}

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

function associate (models) {
  Author.belongsTo(models.Pod, {
    foreignKey: {
      name: 'podId',
      allowNull: true
    },
    onDelete: 'cascade'
  })

  Author.belongsTo(models.User, {
    foreignKey: {
      name: 'userId',
      allowNull: true
    },
    onDelete: 'cascade'
  })
}

findOrCreateAuthor = function (name: string, podId: number, userId: number, transaction: Sequelize.Transaction) {
  const author = {
    name,
    podId,
    userId
  }

  const query: Sequelize.FindOrInitializeOptions<AuthorAttributes> = {
    where: author,
    defaults: author,
    transaction
  }

  return Author.findOrCreate(query).then(([ authorInstance ]) => authorInstance)
}