2016-12-24 16:59:17 +01:00
|
|
|
'use strict'
|
|
|
|
|
2016-12-29 18:02:03 +01:00
|
|
|
const each = require('async/each')
|
|
|
|
|
2016-12-24 16:59:17 +01:00
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
module.exports = function (sequelize, DataTypes) {
|
|
|
|
const Tag = sequelize.define('Tag',
|
|
|
|
{
|
|
|
|
name: {
|
2016-12-28 15:49:23 +01:00
|
|
|
type: DataTypes.STRING,
|
|
|
|
allowNull: false
|
2016-12-24 16:59:17 +01:00
|
|
|
}
|
|
|
|
},
|
|
|
|
{
|
2016-12-29 09:33:28 +01:00
|
|
|
timestamps: false,
|
|
|
|
indexes: [
|
|
|
|
{
|
|
|
|
fields: [ 'name' ],
|
|
|
|
unique: true
|
|
|
|
}
|
|
|
|
],
|
2016-12-24 16:59:17 +01:00
|
|
|
classMethods: {
|
2016-12-29 18:02:03 +01:00
|
|
|
associate,
|
|
|
|
|
|
|
|
findOrCreateTags
|
2016-12-24 16:59:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
return Tag
|
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
function associate (models) {
|
|
|
|
this.belongsToMany(models.Video, {
|
|
|
|
foreignKey: 'tagId',
|
|
|
|
through: models.VideoTag,
|
|
|
|
onDelete: 'cascade'
|
|
|
|
})
|
|
|
|
}
|
2016-12-29 18:02:03 +01:00
|
|
|
|
|
|
|
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)
|
|
|
|
})
|
|
|
|
}
|