]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/tag.js
Server: add video abuse support
[github/Chocobozzz/PeerTube.git] / server / models / tag.js
index 874e88842c106f6714aea6f83effeee3e75cd497..145e090c116fbee01aad4707fdb3aaa6bd3a0f15 100644 (file)
@@ -1,17 +1,29 @@
 'use strict'
 
+const each = require('async/each')
+
 // ---------------------------------------------------------------------------
 
 module.exports = function (sequelize, DataTypes) {
   const Tag = sequelize.define('Tag',
     {
       name: {
-        type: DataTypes.STRING
+        type: DataTypes.STRING,
+        allowNull: false
       }
     },
     {
+      timestamps: false,
+      indexes: [
+        {
+          fields: [ 'name' ],
+          unique: true
+        }
+      ],
       classMethods: {
-        associate
+        associate,
+
+        findOrCreateTags
       }
     }
   )
@@ -28,3 +40,37 @@ function associate (models) {
     onDelete: 'cascade'
   })
 }
+
+function findOrCreateTags (tags, transaction, callback) {
+  if (!callback) {
+    callback = transaction
+    transaction = null
+  }
+
+  const self = this
+  const tagInstances = []
+
+  each(tags, function (tag, callbackEach) {
+    const query = {
+      where: {
+        name: tag
+      },
+      defaults: {
+        name: tag
+      }
+    }
+
+    if (transaction) query.transaction = transaction
+
+    self.findOrCreate(query).asCallback(function (err, res) {
+      if (err) return callbackEach(err)
+
+      // res = [ tag, isCreated ]
+      const tag = res[0]
+      tagInstances.push(tag)
+      return callbackEach()
+    })
+  }, function (err) {
+    return callback(err, tagInstances)
+  })
+}