2017-05-22 18:58:25 +00:00
|
|
|
import * as Sequelize from 'sequelize'
|
2017-07-05 11:26:25 +00:00
|
|
|
import * as Promise from 'bluebird'
|
2016-12-29 17:02:03 +00:00
|
|
|
|
2017-06-16 07:45:46 +00:00
|
|
|
import { addMethodsToModel } from '../utils'
|
2017-05-22 18:58:25 +00:00
|
|
|
import {
|
|
|
|
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,
|
2017-07-11 14:01:56 +00:00
|
|
|
onDelete: 'CASCADE'
|
2016-12-24 15:59:17 +00:00
|
|
|
})
|
|
|
|
}
|
2016-12-29 17:02:03 +00:00
|
|
|
|
2017-07-05 11:26:25 +00:00
|
|
|
findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction) {
|
|
|
|
const tasks: Promise<TagInstance>[] = []
|
|
|
|
tags.forEach(tag => {
|
2017-07-11 08:59:13 +00:00
|
|
|
const query: Sequelize.FindOrInitializeOptions<TagAttributes> = {
|
2016-12-29 17:02:03 +00:00
|
|
|
where: {
|
|
|
|
name: tag
|
|
|
|
},
|
|
|
|
defaults: {
|
|
|
|
name: tag
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (transaction) query.transaction = transaction
|
|
|
|
|
2017-07-05 11:26:25 +00:00
|
|
|
const promise = Tag.findOrCreate(query).then(([ tagInstance ]) => tagInstance)
|
|
|
|
tasks.push(promise)
|
2016-12-29 17:02:03 +00:00
|
|
|
})
|
2017-07-05 11:26:25 +00:00
|
|
|
|
|
|
|
return Promise.all(tasks)
|
2016-12-29 17:02:03 +00:00
|
|
|
}
|