PeerTube/server/models/tag.ts

82 lines
1.7 KiB
TypeScript
Raw Normal View History

2017-05-15 22:22:03 +02:00
import { each } from 'async'
2017-05-22 20:58:25 +02:00
import * as Sequelize from 'sequelize'
2016-12-29 18:02:03 +01:00
2017-05-22 20:58:25 +02:00
import { addMethodsToModel } from './utils'
import {
TagClass,
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-29 18:02:03 +01:00
2017-06-10 22:15:25 +02:00
findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction, callback: TagMethods.FindOrCreateTagsCallback) {
2016-12-29 18:02:03 +01:00
const tagInstances = []
2017-06-10 22:15:25 +02:00
each<string, Error>(tags, function (tag, callbackEach) {
2017-05-15 22:22:03 +02:00
const query: any = {
2016-12-29 18:02:03 +01:00
where: {
name: tag
},
defaults: {
name: tag
}
}
if (transaction) query.transaction = transaction
2017-05-22 20:58:25 +02:00
Tag.findOrCreate(query).asCallback(function (err, res) {
2016-12-29 18:02:03 +01:00
if (err) return callbackEach(err)
// res = [ tag, isCreated ]
const tag = res[0]
tagInstances.push(tag)
return callbackEach()
})
}, function (err) {
return callback(err, tagInstances)
})
}