Add MANAGE_PEERTUBE_FOLLOW right
[oweals/peertube.git] / server / models / account / account-follow.ts
1 import { values } from 'lodash'
2 import * as Sequelize from 'sequelize'
3
4 import { addMethodsToModel } from '../utils'
5 import { AccountFollowAttributes, AccountFollowInstance, AccountFollowMethods } from './account-follow-interface'
6 import { FOLLOW_STATES } from '../../initializers/constants'
7
8 let AccountFollow: Sequelize.Model<AccountFollowInstance, AccountFollowAttributes>
9 let loadByAccountAndTarget: AccountFollowMethods.LoadByAccountAndTarget
10
11 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
12   AccountFollow = sequelize.define<AccountFollowInstance, AccountFollowAttributes>('AccountFollow',
13     {
14       state: {
15         type: DataTypes.ENUM(values(FOLLOW_STATES)),
16         allowNull: false
17       }
18     },
19     {
20       indexes: [
21         {
22           fields: [ 'accountId' ],
23           unique: true
24         },
25         {
26           fields: [ 'targetAccountId' ],
27           unique: true
28         }
29       ]
30     }
31   )
32
33   const classMethods = [
34     associate
35   ]
36   addMethodsToModel(AccountFollow, classMethods)
37
38   return AccountFollow
39 }
40
41 // ------------------------------ STATICS ------------------------------
42
43 function associate (models) {
44   AccountFollow.belongsTo(models.Account, {
45     foreignKey: {
46       name: 'accountId',
47       allowNull: false
48     },
49     as: 'followers',
50     onDelete: 'CASCADE'
51   })
52
53   AccountFollow.belongsTo(models.Account, {
54     foreignKey: {
55       name: 'targetAccountId',
56       allowNull: false
57     },
58     as: 'following',
59     onDelete: 'CASCADE'
60   })
61 }
62
63 loadByAccountAndTarget = function (accountId: number, targetAccountId: number) {
64   const query = {
65     where: {
66       accountId,
67       targetAccountId
68     }
69   }
70
71   return AccountFollow.findOne(query)
72 }