1
0
Fork 0
peertube/server/models/tag.ts

75 lines
1.4 KiB
TypeScript
Raw Normal View History

2017-05-15 20:22:03 +00:00
import { each } from 'async'
2016-12-29 17:02:03 +00:00
2016-12-24 15:59:17 +00:00
// ---------------------------------------------------------------------------
module.exports = function (sequelize, DataTypes) {
const Tag = sequelize.define('Tag',
{
name: {
2016-12-28 14:49:23 +00:00
type: DataTypes.STRING,
allowNull: false
2016-12-24 15:59:17 +00:00
}
},
{
2016-12-29 08:33:28 +00:00
timestamps: false,
indexes: [
{
fields: [ 'name' ],
unique: true
}
],
2016-12-24 15:59:17 +00:00
classMethods: {
2016-12-29 17:02:03 +00:00
associate,
findOrCreateTags
2016-12-24 15:59:17 +00:00
}
}
)
return Tag
}
// ---------------------------------------------------------------------------
function associate (models) {
this.belongsToMany(models.Video, {
foreignKey: 'tagId',
through: models.VideoTag,
onDelete: 'cascade'
})
}
2016-12-29 17:02:03 +00:00
function findOrCreateTags (tags, transaction, callback) {
if (!callback) {
callback = transaction
transaction = null
}
const self = this
const tagInstances = []
each(tags, function (tag, callbackEach) {
2017-05-15 20:22:03 +00:00
const query: any = {
2016-12-29 17:02:03 +00:00
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)
})
}