PeerTube/server/models/tag.ts

82 lines
1.7 KiB
TypeScript
Raw Normal View History

2017-05-15 20:22:03 +00:00
import { each } from 'async'
2017-05-22 18:58:25 +00:00
import * as Sequelize from 'sequelize'
2016-12-29 17:02:03 +00:00
2017-05-22 18:58:25 +00:00
import { addMethodsToModel } from './utils'
import {
TagClass,
TagInstance,
TagAttributes,
TagMethods
} from './tag-interface'
2016-12-24 15:59:17 +00:00
2017-05-22 18:58:25 +00:00
let Tag: Sequelize.Model<TagInstance, TagAttributes>
let findOrCreateTags: TagMethods.FindOrCreateTags
2017-06-11 15:35:32 +00:00
export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
Tag = sequelize.define<TagInstance, TagAttributes>('Tag',
2016-12-24 15:59:17 +00:00
{
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
}
2017-05-22 18:58:25 +00:00
]
2016-12-24 15:59:17 +00:00
}
)
2017-05-22 18:58:25 +00:00
const classMethods = [
associate,
findOrCreateTags
]
addMethodsToModel(Tag, classMethods)
2016-12-24 15:59:17 +00:00
return Tag
}
// ---------------------------------------------------------------------------
function associate (models) {
2017-05-22 18:58:25 +00:00
Tag.belongsToMany(models.Video, {
2016-12-24 15:59:17 +00:00
foreignKey: 'tagId',
through: models.VideoTag,
onDelete: 'cascade'
})
}
2016-12-29 17:02:03 +00:00
2017-06-10 20:15:25 +00:00
findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction, callback: TagMethods.FindOrCreateTagsCallback) {
2016-12-29 17:02:03 +00:00
const tagInstances = []
2017-06-10 20:15:25 +00:00
each<string, Error>(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
2017-05-22 18:58:25 +00:00
Tag.findOrCreate(query).asCallback(function (err, res) {
2016-12-29 17:02:03 +00:00
if (err) return callbackEach(err)
// res = [ tag, isCreated ]
const tag = res[0]
tagInstances.push(tag)
return callbackEach()
})
}, function (err) {
return callback(err, tagInstances)
})
}