]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/tag.ts
First typescript iteration
[github/Chocobozzz/PeerTube.git] / server / models / tag.ts
1 import { each } from 'async'
2
3 // ---------------------------------------------------------------------------
4
5 module.exports = function (sequelize, DataTypes) {
6 const Tag = sequelize.define('Tag',
7 {
8 name: {
9 type: DataTypes.STRING,
10 allowNull: false
11 }
12 },
13 {
14 timestamps: false,
15 indexes: [
16 {
17 fields: [ 'name' ],
18 unique: true
19 }
20 ],
21 classMethods: {
22 associate,
23
24 findOrCreateTags
25 }
26 }
27 )
28
29 return Tag
30 }
31
32 // ---------------------------------------------------------------------------
33
34 function associate (models) {
35 this.belongsToMany(models.Video, {
36 foreignKey: 'tagId',
37 through: models.VideoTag,
38 onDelete: 'cascade'
39 })
40 }
41
42 function findOrCreateTags (tags, transaction, callback) {
43 if (!callback) {
44 callback = transaction
45 transaction = null
46 }
47
48 const self = this
49 const tagInstances = []
50
51 each(tags, function (tag, callbackEach) {
52 const query: any = {
53 where: {
54 name: tag
55 },
56 defaults: {
57 name: tag
58 }
59 }
60
61 if (transaction) query.transaction = transaction
62
63 self.findOrCreate(query).asCallback(function (err, res) {
64 if (err) return callbackEach(err)
65
66 // res = [ tag, isCreated ]
67 const tag = res[0]
68 tagInstances.push(tag)
69 return callbackEach()
70 })
71 }, function (err) {
72 return callback(err, tagInstances)
73 })
74 }