Client: add views information and sort
[oweals/peertube.git] / server / models / author.js
index e0ac868eab7384536670305cffa9258e73735c43..34b0130971e12db40f7cd4043f2985734d3ba6f5 100644 (file)
@@ -17,8 +17,26 @@ module.exports = function (sequelize, DataTypes) {
       }
     },
     {
+      indexes: [
+        {
+          fields: [ 'name' ]
+        },
+        {
+          fields: [ 'podId' ]
+        },
+        {
+          fields: [ 'userId' ],
+          unique: true
+        },
+        {
+          fields: [ 'name', 'podId' ],
+          unique: true
+        }
+      ],
       classMethods: {
-        associate
+        associate,
+
+        findOrCreateAuthor
       }
     }
   )
@@ -36,4 +54,39 @@ function associate (models) {
     },
     onDelete: 'cascade'
   })
+
+  this.belongsTo(models.User, {
+    foreignKey: {
+      name: 'userId',
+      allowNull: true
+    },
+    onDelete: 'cascade'
+  })
+}
+
+function findOrCreateAuthor (name, podId, userId, transaction, callback) {
+  if (!callback) {
+    callback = transaction
+    transaction = null
+  }
+
+  const author = {
+    name,
+    podId,
+    userId
+  }
+
+  const query = {
+    where: author,
+    defaults: author
+  }
+
+  if (transaction) query.transaction = transaction
+
+  this.findOrCreate(query).asCallback(function (err, result) {
+    if (err) return callback(err)
+
+    // [ instance, wasCreated ]
+    return callback(null, result[0])
+  })
 }