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