Use global uuid instead of remoteId for videos
[oweals/peertube.git] / server / models / video / tag.ts
1 import * as Sequelize from 'sequelize'
2 import * as Promise from 'bluebird'
3
4 import { addMethodsToModel } from '../utils'
5 import {
6   TagInstance,
7   TagAttributes,
8
9   TagMethods
10 } from './tag-interface'
11
12 let Tag: Sequelize.Model<TagInstance, TagAttributes>
13 let findOrCreateTags: TagMethods.FindOrCreateTags
14
15 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
16   Tag = sequelize.define<TagInstance, TagAttributes>('Tag',
17     {
18       name: {
19         type: DataTypes.STRING,
20         allowNull: false
21       }
22     },
23     {
24       timestamps: false,
25       indexes: [
26         {
27           fields: [ 'name' ],
28           unique: true
29         }
30       ]
31     }
32   )
33
34   const classMethods = [
35     associate,
36
37     findOrCreateTags
38   ]
39   addMethodsToModel(Tag, classMethods)
40
41   return Tag
42 }
43
44 // ---------------------------------------------------------------------------
45
46 function associate (models) {
47   Tag.belongsToMany(models.Video, {
48     foreignKey: 'tagId',
49     through: models.VideoTag,
50     onDelete: 'CASCADE'
51   })
52 }
53
54 findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction) {
55   const tasks: Promise<TagInstance>[] = []
56   tags.forEach(tag => {
57     const query: Sequelize.FindOrInitializeOptions<TagAttributes> = {
58       where: {
59         name: tag
60       },
61       defaults: {
62         name: tag
63       }
64     }
65
66     if (transaction) query.transaction = transaction
67
68     const promise = Tag.findOrCreate(query).then(([ tagInstance ]) => tagInstance)
69     tasks.push(promise)
70   })
71
72   return Promise.all(tasks)
73 }