Fix well known and json parser with mastodon
[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) {
56   return VideoShare.findOne({
57     where: {
58       accountId,
59       videoId
60     },
61     include: [
62       VideoShare['sequelize'].models.Account
63     ]
64   })
65 }
66
67 loadAccountsByShare = function (videoId: number) {
68   const query = {
69     where: {
70       videoId
71     },
72     include: [
73       {
74         model: VideoShare['sequelize'].models.Account,
75         required: true
76       }
77     ]
78   }
79
80   return VideoShare.findAll(query)
81     .then(res => res.map(r => r.Account))
82 }