]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/server/server-blocklist.ts
Stronger model typings
[github/Chocobozzz/PeerTube.git] / server / models / server / server-blocklist.ts
1 import { BelongsTo, Column, CreatedAt, ForeignKey, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
2 import { AccountModel } from '../account/account'
3 import { ServerModel } from './server'
4 import { ServerBlock } from '../../../shared/models/blocklist'
5 import { getSort } from '../utils'
6 import * as Bluebird from 'bluebird'
7 import { MServerBlocklist, MServerBlocklistAccountServer } from '@server/typings/models'
8
9 enum ScopeNames {
10 WITH_ACCOUNT = 'WITH_ACCOUNT',
11 WITH_SERVER = 'WITH_SERVER'
12 }
13
14 @Scopes(() => ({
15 [ScopeNames.WITH_ACCOUNT]: {
16 include: [
17 {
18 model: AccountModel,
19 required: true
20 }
21 ]
22 },
23 [ScopeNames.WITH_SERVER]: {
24 include: [
25 {
26 model: ServerModel,
27 required: true
28 }
29 ]
30 }
31 }))
32
33 @Table({
34 tableName: 'serverBlocklist',
35 indexes: [
36 {
37 fields: [ 'accountId', 'targetServerId' ],
38 unique: true
39 },
40 {
41 fields: [ 'targetServerId' ]
42 }
43 ]
44 })
45 export class ServerBlocklistModel extends Model<ServerBlocklistModel> {
46
47 @CreatedAt
48 createdAt: Date
49
50 @UpdatedAt
51 updatedAt: Date
52
53 @ForeignKey(() => AccountModel)
54 @Column
55 accountId: number
56
57 @BelongsTo(() => AccountModel, {
58 foreignKey: {
59 name: 'accountId',
60 allowNull: false
61 },
62 onDelete: 'CASCADE'
63 })
64 ByAccount: AccountModel
65
66 @ForeignKey(() => ServerModel)
67 @Column
68 targetServerId: number
69
70 @BelongsTo(() => ServerModel, {
71 foreignKey: {
72 allowNull: false
73 },
74 onDelete: 'CASCADE'
75 })
76 BlockedServer: ServerModel
77
78 static loadByAccountAndHost (accountId: number, host: string): Bluebird<MServerBlocklist> {
79 const query = {
80 where: {
81 accountId
82 },
83 include: [
84 {
85 model: ServerModel,
86 where: {
87 host
88 },
89 required: true
90 }
91 ]
92 }
93
94 return ServerBlocklistModel.findOne(query)
95 }
96
97 static listForApi (accountId: number, start: number, count: number, sort: string) {
98 const query = {
99 offset: start,
100 limit: count,
101 order: getSort(sort),
102 where: {
103 accountId
104 }
105 }
106
107 return ServerBlocklistModel
108 .scope([ ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_SERVER ])
109 .findAndCountAll<MServerBlocklistAccountServer>(query)
110 .then(({ rows, count }) => {
111 return { total: count, data: rows }
112 })
113 }
114
115 toFormattedJSON (): ServerBlock {
116 return {
117 byAccount: this.ByAccount.toFormattedJSON(),
118 blockedServer: this.BlockedServer.toFormattedJSON(),
119 createdAt: this.createdAt
120 }
121 }
122 }