aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/video/video-share.ts
blob: 22ac31a4a04a917bccaa55c685bb9474c499dbac (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
import * as Sequelize from 'sequelize'

import { addMethodsToModel } from '../utils'
import { VideoShareAttributes, VideoShareInstance, VideoShareMethods } from './video-share-interface'

let VideoShare: Sequelize.Model<VideoShareInstance, VideoShareAttributes>
let loadAccountsByShare: VideoShareMethods.LoadAccountsByShare

export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
  VideoShare = sequelize.define<VideoShareInstance, VideoShareAttributes>('VideoShare',
    { },
    {
      indexes: [
        {
          fields: [ 'accountId' ]
        },
        {
          fields: [ 'videoId' ]
        }
      ]
    }
  )

  const classMethods = [
    associate,
    loadAccountsByShare
  ]
  addMethodsToModel(VideoShare, classMethods)

  return VideoShare
}

// ------------------------------ METHODS ------------------------------

function associate (models) {
  VideoShare.belongsTo(models.Account, {
    foreignKey: {
      name: 'accountId',
      allowNull: false
    },
    onDelete: 'cascade'
  })

  VideoShare.belongsTo(models.Video, {
    foreignKey: {
      name: 'videoId',
      allowNull: true
    },
    onDelete: 'cascade'
  })
}

loadAccountsByShare = function (videoId: number) {
  const query = {
    where: {
      videoId
    },
    include: [
      {
        model: VideoShare['sequelize'].models.Account,
        required: true
      }
    ]
  }

  return VideoShare.findAll(query)
    .then(res => res.map(r => r.Account))
}