]>
Commit | Line | Data |
---|---|---|
e02643f3 | 1 | import * as Sequelize from 'sequelize' |
6fcd19ba | 2 | import * as Promise from 'bluebird' |
4ff0d862 | 3 | |
74889a71 | 4 | import { addMethodsToModel } from '../utils' |
e02643f3 | 5 | import { |
e02643f3 C |
6 | TagInstance, |
7 | TagAttributes, | |
8 | ||
9 | TagMethods | |
10 | } from './tag-interface' | |
7920c273 | 11 | |
e02643f3 C |
12 | let Tag: Sequelize.Model<TagInstance, TagAttributes> |
13 | let findOrCreateTags: TagMethods.FindOrCreateTags | |
14 | ||
127944aa C |
15 | export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) { |
16 | Tag = sequelize.define<TagInstance, TagAttributes>('Tag', | |
7920c273 C |
17 | { |
18 | name: { | |
67bf9b96 C |
19 | type: DataTypes.STRING, |
20 | allowNull: false | |
7920c273 C |
21 | } |
22 | }, | |
23 | { | |
319d072e C |
24 | timestamps: false, |
25 | indexes: [ | |
26 | { | |
27 | fields: [ 'name' ], | |
28 | unique: true | |
29 | } | |
e02643f3 | 30 | ] |
7920c273 C |
31 | } |
32 | ) | |
33 | ||
e02643f3 C |
34 | const classMethods = [ |
35 | associate, | |
36 | ||
37 | findOrCreateTags | |
38 | ] | |
39 | addMethodsToModel(Tag, classMethods) | |
40 | ||
7920c273 C |
41 | return Tag |
42 | } | |
43 | ||
44 | // --------------------------------------------------------------------------- | |
45 | ||
46 | function associate (models) { | |
e02643f3 | 47 | Tag.belongsToMany(models.Video, { |
7920c273 C |
48 | foreignKey: 'tagId', |
49 | through: models.VideoTag, | |
50 | onDelete: 'cascade' | |
51 | }) | |
52 | } | |
4ff0d862 | 53 | |
6fcd19ba C |
54 | findOrCreateTags = function (tags: string[], transaction: Sequelize.Transaction) { |
55 | const tasks: Promise<TagInstance>[] = [] | |
56 | tags.forEach(tag => { | |
65fcc311 | 57 | const query: any = { |
4ff0d862 C |
58 | where: { |
59 | name: tag | |
60 | }, | |
61 | defaults: { | |
62 | name: tag | |
63 | } | |
64 | } | |
65 | ||
66 | if (transaction) query.transaction = transaction | |
67 | ||
6fcd19ba C |
68 | const promise = Tag.findOrCreate(query).then(([ tagInstance ]) => tagInstance) |
69 | tasks.push(promise) | |
4ff0d862 | 70 | }) |
6fcd19ba C |
71 | |
72 | return Promise.all(tasks) | |
4ff0d862 | 73 | } |