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