avatar.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { join } from 'path'
  2. import { AfterDestroy, AllowNull, Column, CreatedAt, Model, Table, UpdatedAt } from 'sequelize-typescript'
  3. import { Avatar } from '../../../shared/models/avatars/avatar.model'
  4. import { CONFIG, STATIC_PATHS } from '../../initializers'
  5. import { logger } from '../../helpers/logger'
  6. import { remove } from 'fs-extra'
  7. @Table({
  8. tableName: 'avatar'
  9. })
  10. export class AvatarModel extends Model<AvatarModel> {
  11. @AllowNull(false)
  12. @Column
  13. filename: string
  14. @CreatedAt
  15. createdAt: Date
  16. @UpdatedAt
  17. updatedAt: Date
  18. @AfterDestroy
  19. static removeFilesAndSendDelete (instance: AvatarModel) {
  20. logger.info('Removing avatar file %s.', instance.filename)
  21. // Don't block the transaction
  22. instance.removeAvatar()
  23. .catch(err => logger.error('Cannot remove avatar file %s.', instance.filename, err))
  24. }
  25. toFormattedJSON (): Avatar {
  26. return {
  27. path: this.getWebserverPath(),
  28. createdAt: this.createdAt,
  29. updatedAt: this.updatedAt
  30. }
  31. }
  32. getWebserverPath () {
  33. return join(STATIC_PATHS.AVATARS, this.filename)
  34. }
  35. removeAvatar () {
  36. const avatarPath = join(CONFIG.STORAGE.AVATARS_DIR, this.filename)
  37. return remove(avatarPath)
  38. }
  39. }