aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/models/avatar/avatar.ts
blob: 51e26c87b3a597bcd8b35c91a7273affd1ce7f15 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { join } from 'path'
import { AfterDestroy, AllowNull, Column, CreatedAt, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { Avatar } from '../../../shared/models/avatars/avatar.model'
import { unlinkPromise } from '../../helpers/core-utils'
import { CONFIG, STATIC_PATHS } from '../../initializers'
import { logger } from '../../helpers/logger'

@Table({
  tableName: 'avatar'
})
export class AvatarModel extends Model<AvatarModel> {

  @AllowNull(false)
  @Column
  filename: string

  @CreatedAt
  createdAt: Date

  @UpdatedAt
  updatedAt: Date

  @AfterDestroy
  static removeFilesAndSendDelete (instance: AvatarModel) {
    logger.info('Removing avatar file %s.', instance.filename)
    return instance.removeAvatar()
  }

  toFormattedJSON (): Avatar {
    return {
      path: this.getWebserverPath(),
      createdAt: this.createdAt,
      updatedAt: this.updatedAt
    }
  }

  getWebserverPath () {
    return join(STATIC_PATHS.AVATARS, this.filename)
  }

  removeAvatar () {
    const avatarPath = join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
    return unlinkPromise(avatarPath)
  }
}