Make some fields optional when uploading a video
[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 let load: VideoChannelShareMethods.Load
9
10 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
11   VideoChannelShare = sequelize.define<VideoChannelShareInstance, VideoChannelShareAttributes>('VideoChannelShare',
12     { },
13     {
14       indexes: [
15         {
16           fields: [ 'accountId' ]
17         },
18         {
19           fields: [ 'videoChannelId' ]
20         }
21       ]
22     }
23   )
24
25   const classMethods = [
26     associate,
27     load,
28     loadAccountsByShare
29   ]
30   addMethodsToModel(VideoChannelShare, classMethods)
31
32   return VideoChannelShare
33 }
34
35 // ------------------------------ METHODS ------------------------------
36
37 function associate (models) {
38   VideoChannelShare.belongsTo(models.Account, {
39     foreignKey: {
40       name: 'accountId',
41       allowNull: false
42     },
43     onDelete: 'cascade'
44   })
45
46   VideoChannelShare.belongsTo(models.VideoChannel, {
47     foreignKey: {
48       name: 'videoChannelId',
49       allowNull: true
50     },
51     onDelete: 'cascade'
52   })
53 }
54
55 load = function (accountId: number, videoChannelId: number, t: Sequelize.Transaction) {
56   return VideoChannelShare.findOne({
57     where: {
58       accountId,
59       videoChannelId
60     },
61     include: [
62       VideoChannelShare['sequelize'].models.Account,
63       VideoChannelShare['sequelize'].models.VideoChannel
64     ],
65     transaction: t
66   })
67 }
68
69 loadAccountsByShare = function (videoChannelId: number, t: Sequelize.Transaction) {
70   const query = {
71     where: {
72       videoChannelId
73     },
74     include: [
75       {
76         model: VideoChannelShare['sequelize'].models.Account,
77         required: true
78       }
79     ],
80     transaction: t
81   }
82
83   return VideoChannelShare.findAll(query)
84     .then(res => res.map(r => r.Account))
85 }