Fix updating video tags to empty field
[oweals/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     if (tags === null) return []
41
42     const tasks: Bluebird<TagModel>[] = []
43     tags.forEach(tag => {
44       const query = {
45         where: {
46           name: tag
47         },
48         defaults: {
49           name: tag
50         }
51       }
52
53       if (transaction) query['transaction'] = transaction
54
55       const promise = TagModel.findOrCreate(query)
56         .then(([ tagInstance ]) => tagInstance)
57       tasks.push(promise)
58     })
59
60     return Promise.all(tasks)
61   }
62 }