]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/tag.js
Update README features
[github/Chocobozzz/PeerTube.git] / server / models / tag.js
index 27eecdc84d20be0ef6310bd566973b2d553fa310..145e090c116fbee01aad4707fdb3aaa6bd3a0f15 100644 (file)
@@ -1,5 +1,7 @@
 'use strict'
 
+const each = require('async/each')
+
 // ---------------------------------------------------------------------------
 
 module.exports = function (sequelize, DataTypes) {
@@ -19,7 +21,9 @@ module.exports = function (sequelize, DataTypes) {
         }
       ],
       classMethods: {
-        associate
+        associate,
+
+        findOrCreateTags
       }
     }
   )
@@ -36,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)
+  })
+}