tag.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import * as Bluebird from 'bluebird'
  2. import { QueryTypes, Transaction } from 'sequelize'
  3. import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
  4. import { isVideoTagValid } from '../../helpers/custom-validators/videos'
  5. import { throwIfNotValid } from '../utils'
  6. import { VideoModel } from './video'
  7. import { VideoTagModel } from './video-tag'
  8. import { VideoPrivacy, VideoState } from '../../../shared/models/videos'
  9. @Table({
  10. tableName: 'tag',
  11. timestamps: false,
  12. indexes: [
  13. {
  14. fields: [ 'name' ],
  15. unique: true
  16. }
  17. ]
  18. })
  19. export class TagModel extends Model<TagModel> {
  20. @AllowNull(false)
  21. @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
  22. @Column
  23. name: string
  24. @CreatedAt
  25. createdAt: Date
  26. @UpdatedAt
  27. updatedAt: Date
  28. @BelongsToMany(() => VideoModel, {
  29. foreignKey: 'tagId',
  30. through: () => VideoTagModel,
  31. onDelete: 'CASCADE'
  32. })
  33. Videos: VideoModel[]
  34. static findOrCreateTags (tags: string[], transaction: Transaction) {
  35. if (tags === null) return []
  36. const tasks: Bluebird<TagModel>[] = []
  37. tags.forEach(tag => {
  38. const query = {
  39. where: {
  40. name: tag
  41. },
  42. defaults: {
  43. name: tag
  44. },
  45. transaction
  46. }
  47. const promise = TagModel.findOrCreate(query)
  48. .then(([ tagInstance ]) => tagInstance)
  49. tasks.push(promise)
  50. })
  51. return Promise.all(tasks)
  52. }
  53. // threshold corresponds to how many video the field should have to be returned
  54. static getRandomSamples (threshold: number, count: number): Bluebird<string[]> {
  55. const query = 'SELECT tag.name FROM tag ' +
  56. 'INNER JOIN "videoTag" ON "videoTag"."tagId" = tag.id ' +
  57. 'INNER JOIN video ON video.id = "videoTag"."videoId" ' +
  58. 'WHERE video.privacy = $videoPrivacy AND video.state = $videoState ' +
  59. 'GROUP BY tag.name HAVING COUNT(tag.name) >= $threshold ' +
  60. 'ORDER BY random() ' +
  61. 'LIMIT $count'
  62. const options = {
  63. bind: { threshold, count, videoPrivacy: VideoPrivacy.PUBLIC, videoState: VideoState.PUBLISHED },
  64. type: QueryTypes.SELECT as QueryTypes.SELECT
  65. }
  66. return TagModel.sequelize.query<{ name: string }>(query, options)
  67. .then(data => data.map(d => d.name))
  68. }
  69. }