2
1

account-blocklist.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import { BelongsTo, Column, CreatedAt, ForeignKey, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
  2. import { AccountModel } from './account'
  3. import { getSort } from '../utils'
  4. import { AccountBlock } from '../../../shared/models/blocklist'
  5. enum ScopeNames {
  6. WITH_ACCOUNTS = 'WITH_ACCOUNTS'
  7. }
  8. @Scopes({
  9. [ScopeNames.WITH_ACCOUNTS]: {
  10. include: [
  11. {
  12. model: () => AccountModel,
  13. required: true,
  14. as: 'ByAccount'
  15. },
  16. {
  17. model: () => AccountModel,
  18. required: true,
  19. as: 'BlockedAccount'
  20. }
  21. ]
  22. }
  23. })
  24. @Table({
  25. tableName: 'accountBlocklist',
  26. indexes: [
  27. {
  28. fields: [ 'accountId', 'targetAccountId' ],
  29. unique: true
  30. },
  31. {
  32. fields: [ 'targetAccountId' ]
  33. }
  34. ]
  35. })
  36. export class AccountBlocklistModel extends Model<AccountBlocklistModel> {
  37. @CreatedAt
  38. createdAt: Date
  39. @UpdatedAt
  40. updatedAt: Date
  41. @ForeignKey(() => AccountModel)
  42. @Column
  43. accountId: number
  44. @BelongsTo(() => AccountModel, {
  45. foreignKey: {
  46. name: 'accountId',
  47. allowNull: false
  48. },
  49. as: 'ByAccount',
  50. onDelete: 'CASCADE'
  51. })
  52. ByAccount: AccountModel
  53. @ForeignKey(() => AccountModel)
  54. @Column
  55. targetAccountId: number
  56. @BelongsTo(() => AccountModel, {
  57. foreignKey: {
  58. name: 'targetAccountId',
  59. allowNull: false
  60. },
  61. as: 'BlockedAccount',
  62. onDelete: 'CASCADE'
  63. })
  64. BlockedAccount: AccountModel
  65. static loadByAccountAndTarget (accountId: number, targetAccountId: number) {
  66. const query = {
  67. where: {
  68. accountId,
  69. targetAccountId
  70. }
  71. }
  72. return AccountBlocklistModel.findOne(query)
  73. }
  74. static listForApi (accountId: number, start: number, count: number, sort: string) {
  75. const query = {
  76. offset: start,
  77. limit: count,
  78. order: getSort(sort),
  79. where: {
  80. accountId
  81. }
  82. }
  83. return AccountBlocklistModel
  84. .scope([ ScopeNames.WITH_ACCOUNTS ])
  85. .findAndCountAll(query)
  86. .then(({ rows, count }) => {
  87. return { total: count, data: rows }
  88. })
  89. }
  90. toFormattedJSON (): AccountBlock {
  91. return {
  92. byAccount: this.ByAccount.toFormattedJSON(),
  93. blockedAccount: this.BlockedAccount.toFormattedJSON(),
  94. createdAt: this.createdAt
  95. }
  96. }
  97. }