PeerTube/server/models/tag.js

77 lines
1.4 KiB
JavaScript
Raw Normal View History

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