]>
Commit | Line | Data |
---|---|---|
3fd3ab2d C |
1 | import * as Bluebird from 'bluebird' |
2 | import { Transaction } from 'sequelize' | |
3 | import { AllowNull, BelongsToMany, Column, CreatedAt, Is, Model, Table, UpdatedAt } from 'sequelize-typescript' | |
4 | import { isVideoTagValid } from '../../helpers/custom-validators/videos' | |
5 | import { throwIfNotValid } from '../utils' | |
6 | import { VideoModel } from './video' | |
7 | import { VideoTagModel } from './video-tag' | |
8 | ||
9 | @Table({ | |
10 | tableName: 'tag', | |
11 | timestamps: false, | |
12 | indexes: [ | |
7920c273 | 13 | { |
3fd3ab2d C |
14 | fields: [ 'name' ], |
15 | unique: true | |
7920c273 | 16 | } |
e02643f3 | 17 | ] |
3fd3ab2d C |
18 | }) |
19 | export class TagModel extends Model<TagModel> { | |
e02643f3 | 20 | |
3fd3ab2d C |
21 | @AllowNull(false) |
22 | @Is('VideoTag', value => throwIfNotValid(value, isVideoTagValid, 'tag')) | |
23 | @Column | |
24 | name: string | |
7920c273 | 25 | |
3fd3ab2d C |
26 | @CreatedAt |
27 | createdAt: Date | |
7920c273 | 28 | |
3fd3ab2d C |
29 | @UpdatedAt |
30 | updatedAt: Date | |
31 | ||
32 | @BelongsToMany(() => VideoModel, { | |
7920c273 | 33 | foreignKey: 'tagId', |
3fd3ab2d | 34 | through: () => VideoTagModel, |
0a6658fd | 35 | onDelete: 'CASCADE' |
7920c273 | 36 | }) |
3fd3ab2d C |
37 | Videos: VideoModel[] |
38 | ||
39 | static findOrCreateTags (tags: string[], transaction: Transaction) { | |
40 | const tasks: Bluebird<TagModel>[] = [] | |
41 | tags.forEach(tag => { | |
42 | const query = { | |
43 | where: { | |
44 | name: tag | |
45 | }, | |
46 | defaults: { | |
47 | name: tag | |
48 | } | |
4ff0d862 | 49 | } |
4ff0d862 | 50 | |
3fd3ab2d | 51 | if (transaction) query['transaction'] = transaction |
4ff0d862 | 52 | |
3fd3ab2d C |
53 | const promise = TagModel.findOrCreate(query) |
54 | .then(([ tagInstance ]) => tagInstance) | |
55 | tasks.push(promise) | |
56 | }) | |
6fcd19ba | 57 | |
3fd3ab2d C |
58 | return Promise.all(tasks) |
59 | } | |
4ff0d862 | 60 | } |