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