PeerTube/server/models/video/tag.ts

74 lines
1.5 KiB
TypeScript
Raw Normal View History

2017-05-22 20:58:25 +02:00
import * as Sequelize from 'sequelize'
import * as Promise from 'bluebird'
2016-12-29 18:02:03 +01:00
2017-06-16 09:45:46 +02:00
import { addMethodsToModel } from '../utils'
2017-05-22 20:58:25 +02:00
import {
TagInstance,
TagAttributes,
TagMethods
} from './tag-interface'
2016-12-24 16:59:17 +01:00
2017-05-22 20:58:25 +02:00
let Tag: Sequelize.Model<TagInstance, TagAttributes>
let findOrCreateTags: TagMethods.FindOrCreateTags
2017-06-11 17:35:32 +02:00
export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
Tag = sequelize.define<TagInstance, TagAttributes>('Tag',
2016-12-24 16:59:17 +01:00
{
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
}
2017-05-22 20:58:25 +02:00
]
2016-12-24 16:59:17 +01:00
}
)
2017-05-22 20:58:25 +02:00
const classMethods = [
associate,
findOrCreateTags
]
addMethodsToModel(Tag, classMethods)
2016-12-24 16:59:17 +01:00
return Tag
}
// ---------------------------------------------------------------------------
function associate (models) {
2017-05-22 20:58:25 +02:00
Tag.belongsToMany(models.Video, {
2016-12-24 16:59:17 +01:00
foreignKey: 'tagId',
through: models.VideoTag,
onDelete: 'CASCADE'
2016-12-24 16:59:17 +01:00
})
}
2016-12-29 18:02:03 +01:00
findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction) {
const tasks: Promise<TagInstance>[] = []
tags.forEach(tag => {
2017-07-11 10:59:13 +02:00
const query: Sequelize.FindOrInitializeOptions<TagAttributes> = {
2016-12-29 18:02:03 +01:00
where: {
name: tag
},
defaults: {
name: tag
}
}
if (transaction) query.transaction = transaction
const promise = Tag.findOrCreate(query).then(([ tagInstance ]) => tagInstance)
tasks.push(promise)
2016-12-29 18:02:03 +01:00
})
return Promise.all(tasks)
2016-12-29 18:02:03 +01:00
}