]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/server/server.ts
Refactor table attributes
[github/Chocobozzz/PeerTube.git] / server / models / server / server.ts
1 import { Transaction } from 'sequelize'
2 import { AllowNull, Column, CreatedAt, Default, HasMany, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
3 import { MServer, MServerFormattable } from '@server/types/models/server'
4 import { AttributesOnly } from '@shared/typescript-utils'
5 import { isHostValid } from '../../helpers/custom-validators/servers'
6 import { ActorModel } from '../actor/actor'
7 import { buildSQLAttributes, throwIfNotValid } from '../utils'
8 import { ServerBlocklistModel } from './server-blocklist'
9
10 @Table({
11 tableName: 'server',
12 indexes: [
13 {
14 fields: [ 'host' ],
15 unique: true
16 }
17 ]
18 })
19 export class ServerModel extends Model<Partial<AttributesOnly<ServerModel>>> {
20
21 @AllowNull(false)
22 @Is('Host', value => throwIfNotValid(value, isHostValid, 'valid host'))
23 @Column
24 host: string
25
26 @AllowNull(false)
27 @Default(false)
28 @Column
29 redundancyAllowed: boolean
30
31 @CreatedAt
32 createdAt: Date
33
34 @UpdatedAt
35 updatedAt: Date
36
37 @HasMany(() => ActorModel, {
38 foreignKey: {
39 name: 'serverId',
40 allowNull: true
41 },
42 onDelete: 'CASCADE',
43 hooks: true
44 })
45 Actors: ActorModel[]
46
47 @HasMany(() => ServerBlocklistModel, {
48 foreignKey: {
49 allowNull: false
50 },
51 onDelete: 'CASCADE'
52 })
53 BlockedBy: ServerBlocklistModel[]
54
55 // ---------------------------------------------------------------------------
56
57 static getSQLAttributes (tableName: string, aliasPrefix = '') {
58 return buildSQLAttributes({
59 model: this,
60 tableName,
61 aliasPrefix
62 })
63 }
64
65 // ---------------------------------------------------------------------------
66
67 static load (id: number, transaction?: Transaction): Promise<MServer> {
68 const query = {
69 where: {
70 id
71 },
72 transaction
73 }
74
75 return ServerModel.findOne(query)
76 }
77
78 static loadByHost (host: string): Promise<MServer> {
79 const query = {
80 where: {
81 host
82 }
83 }
84
85 return ServerModel.findOne(query)
86 }
87
88 static async loadOrCreateByHost (host: string) {
89 let server = await ServerModel.loadByHost(host)
90 if (!server) server = await ServerModel.create({ host })
91
92 return server
93 }
94
95 isBlocked () {
96 return this.BlockedBy && this.BlockedBy.length !== 0
97 }
98
99 toFormattedJSON (this: MServerFormattable) {
100 return {
101 host: this.host
102 }
103 }
104 }