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