]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/tag.ts
3c657d7517961d71a0aec962c96f4e96668385b8
[github/Chocobozzz/PeerTube.git] / server / models / video / tag.ts
1 import { each } from 'async'
2 import * as Sequelize from 'sequelize'
3
4 import { addMethodsToModel } from '../utils'
5 import {
6 TagClass,
7 TagInstance,
8 TagAttributes,
9
10 TagMethods
11 } from './tag-interface'
12
13 let Tag: Sequelize.Model<TagInstance, TagAttributes>
14 let findOrCreateTags: TagMethods.FindOrCreateTags
15
16 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
17 Tag = sequelize.define<TagInstance, TagAttributes>('Tag',
18 {
19 name: {
20 type: DataTypes.STRING,
21 allowNull: false
22 }
23 },
24 {
25 timestamps: false,
26 indexes: [
27 {
28 fields: [ 'name' ],
29 unique: true
30 }
31 ]
32 }
33 )
34
35 const classMethods = [
36 associate,
37
38 findOrCreateTags
39 ]
40 addMethodsToModel(Tag, classMethods)
41
42 return Tag
43 }
44
45 // ---------------------------------------------------------------------------
46
47 function associate (models) {
48 Tag.belongsToMany(models.Video, {
49 foreignKey: 'tagId',
50 through: models.VideoTag,
51 onDelete: 'cascade'
52 })
53 }
54
55 findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction, callback: TagMethods.FindOrCreateTagsCallback) {
56 const tagInstances = []
57
58 each<string, Error>(tags, function (tag, callbackEach) {
59 const query: any = {
60 where: {
61 name: tag
62 },
63 defaults: {
64 name: tag
65 }
66 }
67
68 if (transaction) query.transaction = transaction
69
70 Tag.findOrCreate(query).asCallback(function (err, res) {
71 if (err) return callbackEach(err)
72
73 // res = [ tag, isCreated ]
74 const tag = res[0]
75 tagInstances.push(tag)
76 return callbackEach()
77 })
78 }, function (err) {
79 return callback(err, tagInstances)
80 })
81 }