Cleanup models
[oweals/peertube.git] / server / models / video / video-share.ts
1 import * as Sequelize from 'sequelize'
2
3 import { addMethodsToModel } from '../utils'
4 import { VideoShareAttributes, VideoShareInstance, VideoShareMethods } from './video-share-interface'
5
6 let VideoShare: Sequelize.Model<VideoShareInstance, VideoShareAttributes>
7 let loadAccountsByShare: VideoShareMethods.LoadAccountsByShare
8
9 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
10   VideoShare = sequelize.define<VideoShareInstance, VideoShareAttributes>('VideoShare',
11     { },
12     {
13       indexes: [
14         {
15           fields: [ 'accountId' ]
16         },
17         {
18           fields: [ 'videoId' ]
19         }
20       ]
21     }
22   )
23
24   const classMethods = [
25     associate,
26     loadAccountsByShare
27   ]
28   addMethodsToModel(VideoShare, classMethods)
29
30   return VideoShare
31 }
32
33 // ------------------------------ METHODS ------------------------------
34
35 function associate (models) {
36   VideoShare.belongsTo(models.Account, {
37     foreignKey: {
38       name: 'accountId',
39       allowNull: false
40     },
41     onDelete: 'cascade'
42   })
43
44   VideoShare.belongsTo(models.Video, {
45     foreignKey: {
46       name: 'videoId',
47       allowNull: true
48     },
49     onDelete: 'cascade'
50   })
51 }
52
53 loadAccountsByShare = function (videoId: number) {
54   const query = {
55     where: {
56       videoId
57     },
58     include: [
59       {
60         model: VideoShare['sequelize'].models.Account,
61         required: true
62       }
63     ]
64   }
65
66   return VideoShare.findAll(query)
67     .then(res => res.map(r => r.Account))
68 }