PeerTube/server/models/video/tag.ts

63 lines
1.4 KiB
TypeScript
Raw Normal View History

2017-12-12 17:53:50 +01:00
import * as Bluebird from 'bluebird'
import { Transaction } from 'sequelize'
import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
import { isVideoTagValid } from '../../helpers/custom-validators/videos'
import { throwIfNotValid } from '../utils'
import { VideoModel } from './video'
import { VideoTagModel } from './video-tag'
@Table({
tableName: 'tag',
timestamps: false,
indexes: [
2016-12-24 16:59:17 +01:00
{
2017-12-12 17:53:50 +01:00
fields: [ 'name' ],
unique: true
2016-12-24 16:59:17 +01:00
}
2017-05-22 20:58:25 +02:00
]
2017-12-12 17:53:50 +01:00
})
export class TagModel extends Model<TagModel> {
2017-05-22 20:58:25 +02:00
2017-12-12 17:53:50 +01:00
@AllowNull(false)
@Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag'))
@Column
name: string
2016-12-24 16:59:17 +01:00
2017-12-12 17:53:50 +01:00
@CreatedAt
createdAt: Date
2016-12-24 16:59:17 +01:00
2017-12-12 17:53:50 +01:00
@UpdatedAt
updatedAt: Date
@BelongsToMany(() => VideoModel, {
2016-12-24 16:59:17 +01:00
foreignKey: 'tagId',
2017-12-12 17:53:50 +01:00
through: () => VideoTagModel,
onDelete: 'CASCADE'
2016-12-24 16:59:17 +01:00
})
2017-12-12 17:53:50 +01:00
Videos: VideoModel[]
static findOrCreateTags (tags: string[], transaction: Transaction) {
2018-05-16 09:28:18 +02:00
if (tags === null) return []
2017-12-12 17:53:50 +01:00
const tasks: Bluebird<TagModel>[] = []
tags.forEach(tag => {
const query = {
where: {
name: tag
},
defaults: {
name: tag
}
2016-12-29 18:02:03 +01:00
}
2017-12-12 17:53:50 +01:00
if (transaction) query['transaction'] = transaction
2016-12-29 18:02:03 +01:00
2017-12-12 17:53:50 +01:00
const promise = TagModel.findOrCreate(query)
.then(([ tagInstance ]) => tagInstance)
tasks.push(promise)
})
2017-12-12 17:53:50 +01:00
return Promise.all(tasks)
}
2016-12-29 18:02:03 +01:00
}