]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/server/server.ts
Move typescript utils in its own directory
[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 { 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 static load (id: number, transaction?: Transaction): Promise<MServer> {
56 const query = {
57 where: {
58 id
59 },
60 transaction
61 }
62
63 return ServerModel.findOne(query)
64 }
65
66 static loadByHost (host: string): Promise<MServer> {
67 const query = {
68 where: {
69 host
70 }
71 }
72
73 return ServerModel.findOne(query)
74 }
75
76 static async loadOrCreateByHost (host: string) {
77 let server = await ServerModel.loadByHost(host)
78 if (!server) server = await ServerModel.create({ host })
79
80 return server
81 }
82
83 isBlocked () {
84 return this.BlockedBy && this.BlockedBy.length !== 0
85 }
86
87 toFormattedJSON (this: MServerFormattable) {
88 return {
89 host: this.host
90 }
91 }
92 }