]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/tag.ts
Video channel API routes refractor
[github/Chocobozzz/PeerTube.git] / server / models / video / tag.ts
1 import * as Bluebird from 'bluebird'
2 import { 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
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
21 @AllowNull(false)
22 @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
23 @Column
24 name: string
25
26 @CreatedAt
27 createdAt: Date
28
29 @UpdatedAt
30 updatedAt: Date
31
32 @BelongsToMany(() => VideoModel, {
33 foreignKey: 'tagId',
34 through: () => VideoTagModel,
35 onDelete: 'CASCADE'
36 })
37 Videos: VideoModel[]
38
39 static findOrCreateTags (tags: string[], transaction: Transaction) {
40 const tasks: Bluebird<TagModel>[] = []
41 tags.forEach(tag => {
42 const query = {
43 where: {
44 name: tag
45 },
46 defaults: {
47 name: tag
48 }
49 }
50
51 if (transaction) query['transaction'] = transaction
52
53 const promise = TagModel.findOrCreate(query)
54 .then(([ tagInstance ]) => tagInstance)
55 tasks.push(promise)
56 })
57
58 return Promise.all(tasks)
59 }
60 }