]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/tag.ts
Type models
[github/Chocobozzz/PeerTube.git] / server / models / 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, DataTypes) {
17 Tag = sequelize.define('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, transaction, callback) {
56 if (!callback) {
57 callback = transaction
58 transaction = null
59 }
60
61 const tagInstances = []
62
63 each(tags, function (tag, callbackEach) {
64 const query: any = {
65 where: {
66 name: tag
67 },
68 defaults: {
69 name: tag
70 }
71 }
72
73 if (transaction) query.transaction = transaction
74
75 Tag.findOrCreate(query).asCallback(function (err, res) {
76 if (err) return callbackEach(err)
77
78 // res = [ tag, isCreated ]
79 const tag = res[0]
80 tagInstances.push(tag)
81 return callbackEach()
82 })
83 }, function (err) {
84 return callback(err, tagInstances)
85 })
86 }