]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/server/server.ts
Stricter models typing
[github/Chocobozzz/PeerTube.git] / server / models / server / server.ts
index 300d7093808c568b76e3520ef8304fafa7fc7522..25d9924fb33e7f91b8fc1f8bb6be01fa002ea8cb 100644 (file)
@@ -1,7 +1,10 @@
 import { AllowNull, Column, CreatedAt, Default, HasMany, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
+import { MServer, MServerFormattable } from '@server/types/models/server'
+import { AttributesOnly } from '@shared/core-utils'
 import { isHostValid } from '../../helpers/custom-validators/servers'
-import { ActorModel } from '../activitypub/actor'
+import { ActorModel } from '../actor/actor'
 import { throwIfNotValid } from '../utils'
+import { ServerBlocklistModel } from './server-blocklist'
 
 @Table({
   tableName: 'server',
@@ -12,7 +15,7 @@ import { throwIfNotValid } from '../utils'
     }
   ]
 })
-export class ServerModel extends Model<ServerModel> {
+export class ServerModel extends Model<Partial<AttributesOnly<ServerModel>>> {
 
   @AllowNull(false)
   @Is('Host', value => throwIfNotValid(value, isHostValid, 'valid host'))
@@ -40,7 +43,25 @@ export class ServerModel extends Model<ServerModel> {
   })
   Actors: ActorModel[]
 
-  static loadByHost (host: string) {
+  @HasMany(() => ServerBlocklistModel, {
+    foreignKey: {
+      allowNull: false
+    },
+    onDelete: 'CASCADE'
+  })
+  BlockedByAccounts: ServerBlocklistModel[]
+
+  static load (id: number): Promise<MServer> {
+    const query = {
+      where: {
+        id
+      }
+    }
+
+    return ServerModel.findOne(query)
+  }
+
+  static loadByHost (host: string): Promise<MServer> {
     const query = {
       where: {
         host
@@ -50,7 +71,18 @@ export class ServerModel extends Model<ServerModel> {
     return ServerModel.findOne(query)
   }
 
-  toFormattedJSON () {
+  static async loadOrCreateByHost (host: string) {
+    let server = await ServerModel.loadByHost(host)
+    if (!server) server = await ServerModel.create({ host })
+
+    return server
+  }
+
+  isBlocked () {
+    return this.BlockedByAccounts && this.BlockedByAccounts.length !== 0
+  }
+
+  toFormattedJSON (this: MServerFormattable) {
     return {
       host: this.host
     }